Rails 3:使用:if语句创建验证

时间:2011-06-18 01:00:21

标签: ruby-on-rails ruby-on-rails-3 validation virtual-attribute

您好我正在尝试设置仅在特定表单视图中调用的验证,为此我尝试在表单上为虚拟属性创建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 %>

3 个答案:

答案 0 :(得分:14)

confirmation_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

答案 1 :(得分:5)

编写一行代码,它可以帮助您简单地组织代码。

validates_presence_of :password_confirmation, :if => lambda {|u| confirmation_validation == '100'}

validates_presence_of :password_confirmation, :if => Proc.new {|u| confirmation_validation == '100'}

答案 2 :(得分:1)

这种反应很晚,但对于未来的SO观众,我认为@Rajesh问题的答案

  

嘿,以上是我的错误,错误如下。无法批量分配受保护的属性。为什么呢?

是否需要在将params散列分配给记录之前从params散列中删除您用作标志的隐藏字段。像

这样的东西
params.reject{|p| p == name_of_hidden_field}