Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails ActiveRecord validation on specific controller and action

is it possible to run ActiveRecord validates on given controller and action.

For example I have user_controller and signup_controller

I need to run password required validation only on signup_controller#create action

like image 731
saygun Avatar asked Apr 07 '14 13:04

saygun


2 Answers

You can run validations using an if conditional:

validates :email, presence: true, if: :validate_email?

Now you need to define this instance method (in your model):

def validate_email?
  validate_email == 'true' || validate_email == true
end

This validate_email attribute could be a virtual attribute in your model:

attr_accessor :validate_email

And now, you can perform email validation depending on that virtual attribute. For example, in signup_controller#create you can do something like:

def create
  ...

  @user.validate_email = true
  @user.save

  ...
end
like image 186
markets Avatar answered Sep 29 '22 00:09

markets


use validates :password, :if => :password_changed? in user.rb

if form in users_controller does not submit password field then you should be ok.

like image 26
firien Avatar answered Sep 29 '22 00:09

firien