ruby-on-rails – Rails 3:使用if语句创建验证

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – Rails 3:使用if语句创建验证前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
嗨,我正在尝试设置一个仅在特定表单视图中调用的验证,为此我试图在窗体上为虚拟属性创建一个hidden_​​field,并将其设置为一个值,然后验证:如果虚拟属性等于该值.

到目前为止我有:

## user model 

validates_presence_of :password_confirmation,:if => :confirmation_validation 

attr_accessible :email,:password,:password_confirmation,:remember_me,:name,:avatar,:username,:bio,:confirmation_validation

def confirmation_validation
 # not sure what goes here???
end


## form view


<%= form_for(resource,:validate => true,:as => resource_name,:url => registration_path(resource_name),:html => { :method => :put },:html => {:multipart => true}) do |f| %>
<%= devise_error_messages! %>

<p><%= f.label :password %> <i>(leave blank if you don't want to change it)</i><br />
<%= f.password_field :password %></p>

<p><%= f.label :password_confirmation %><br />
<%= f.password_field :password_confirmation %>
<% f.hidden_field :confirmation_validation,:value => 100%></p>

<p><%= f.submit "Update" %></p>
<% end %>

解决方法

confirm_validation隐藏字段的值应该包含在params哈希中,并且相应地设置虚拟属性.因此,您可以简单地检查该值是否被设置:
validates_presence_of :password_confirmation,:if => :should_confirm?

def should_confirm?
  confirmation_validation == '100' # Value of the hidden field as set in the form
end
原文链接:https://www.f2er.com/ruby/265655.html

猜你在找的Ruby相关文章