Rails 3: creating a validation with :if statement

11,491

Solution 1

The value of the confirmation_validation hidden field should be included in the params hash, and also set the virtual attribute accordingly. Therefore, you can probably simply check whether or not the value has been set:

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

Solution 2

write one line code, it could help you to organize your code in simple.

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

or

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

Solution 3

This response is very late, but for future SO viewers, I think the answer to @Rajesh question

Hey, the above is showing an error for me and the error is given below. Cant mass-assign protected attributes. Why?

Is that you need to remove the hidden field you are using as a flag from the params hash before it's assigned to the record. Something like

params.reject{|p| p == name_of_hidden_field} 
Share:
11,491
trying_hal9000
Author by

trying_hal9000

Updated on June 21, 2022

Comments

  • trying_hal9000
    trying_hal9000 almost 2 years

    Hi I'm trying to setup a validation that is only called in a specific form view, to do this I'm trying to create a hidden_field for a virtual attribute on the form and set this to a value, then validate :if the virtual attribute equals the value.

    So far I have:

    ## 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 %>
    
  • Rajesh Omanakuttan
    Rajesh Omanakuttan over 11 years
    Hey, the above is showing an error for me and the error is given below. Cant mass-assign proetected attributes. Why?
  • scarver2
    scarver2 almost 11 years
    @Rajesh Add :password_confirmation to your attr_accessible.