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

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...