2

I want to skip some model validation for controller functions. I am doing like this

Model :

attr_accessible :skip_method_2
validates :name,  presence: true, length: { maximum: 50 }, :unless => :skip_method_2
VALID_PHONE_REGEX = /\(?([0-9]{3})\)?([ .-]?)([0-9]{3})\2([0-9]{4})/
validates :phoneno, presence: true,uniqueness: { case_sensitive: false, :scope => :user_id}, format: { with: VALID_PHONE_REGEX }, :unless => :skip_method_2

Controller :

def contacts_callback
 @contacts = request.env['omnicontacts.contacts']   
 @contacts.each do |contact|
   next if current_user.contacts.exists?(:email => "#{contact[:email]}")
   contact1 = current_user.contacts.new(:skip_method_2 => true)
   contact1.name = contact[:name] 
   contact1.email = contact[:email]
   contact1.group = "Others"
   contact1.save
 end
  redirect_to "/contact"
end

I dont want to save it by :validation => false. I want to skip name and phoneno validation for contacts_callback function. But it is not working.

It gives error in controller - undefined local variable or method `skip_method_2' for contacts_callback. I already mentioned attr_accessible in my model

Free-Minded
  • 5,322
  • 6
  • 50
  • 93
  • you only declared skip_method_2 as attr_accessible. have you declared it in attr_accessor? – jvnill Feb 19 '13 at 07:23
  • Yes i am using attr_writer also but it shows error in controller undefined local variable or method `skip_method_2' for contacts_callback – Free-Minded Feb 19 '13 at 07:24
  • no it should be attr_accessor because you need to write to it and you need to read it – jvnill Feb 19 '13 at 07:27
  • I am using both attr_accessor and attr_writer but still it is not working – Free-Minded Feb 19 '13 at 07:38
  • Does this answer your question? [skip certain validation method in Model](https://stackoverflow.com/questions/8881712/skip-certain-validation-method-in-model) – fkoessler Mar 01 '22 at 16:38

1 Answers1

2

Change validates :name, presence: true, length: { maximum: 50 }, :unless => :skip_method_2

to

validates :name, presence: true, length: { maximum: 50 }, :unless => lambda {|x| x.skip_method_2}

Also checkout this answer

Community
  • 1
  • 1
benchwarmer
  • 2,764
  • 23
  • 25