【问题标题】:Rails 3: creating a validation with :if statementRails 3:使用 :if 语句创建验证
【发布时间】:2011-06-18 01:00:21
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:

    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
    

    【讨论】:

    • 嘿,上面对我显示了一个错误,下面给出了错误。无法批量分配受保护的属性。为什么?
    • @Rajesh 将 :password_confirmation 添加到您的 attr_accessible。
    【解决方案2】:

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

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

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

    【讨论】:

      【解决方案3】:

      这个回复很晚,但对于未来的SO观众,我认为@Rajesh问题的答案

      嘿,上面对我显示了一个错误,下面给出了错误。不能批量分配受保护的属性。为什么?

      在将其分配给记录之前,您是否需要从参数哈希中删除您用作标志的隐藏字段。像

      params.reject{|p| p == name_of_hidden_field} 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-08-11
        • 1970-01-01
        • 1970-01-01
        • 2011-08-02
        • 2012-05-06
        • 2012-11-12
        • 1970-01-01
        相关资源
        最近更新 更多