Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validating all attributes except one in Rails

I'm trying to do a custom validation in my model using valid? method. I need to run all validations of this model, except the password.

Something like this:

@resource = SalesPartner.new(permitted_params.merge(parent: current_sales_partner))

respond_to do |format|

  if @resource.valid?(except: :password)
    @resource.generate_authentication_token

    SalesPartnerMailer.mail_new_sales_partner(@resource.email,
      { auth_token: @resource.authentication_token, id: @resource.id, level: @resource.level }
    ).deliver

    flash[:success] = "#{@resource.level} criado com sucesso."
    format.html { render "#{@path}/index" }
  else
    logger.log_and_alert_save_error(@resource, flash, "Ocorreu um erro ao salvar.")
    format.html { render "#{@path}/new" }
  end

end

Is that possible?

Thanks everyone!

like image 904
thiagotonon Avatar asked Aug 18 '15 17:08

thiagotonon


2 Answers

Any way here is a way that you can do with the help of context. Say you have a User model and you want to validates some fields.

validates_presence_of :name,: email, on: :special_context
validates_presence_of :name,:email, :password

With the above 2 lines, you can now do like below

@user.valid?(:special_context)

The above will validates name and email fields. And if you write now,

@user.valid?

This will perform the presence validations on the name, email and password fields as you wrote.

Read valid?(context = nil) to understand the context.

Runs all the validations within the specified context. If the argument is false (default is nil), the context is set to :create if new_record? is true, and to :update if it is not.

Validations with no :on option will run no matter the context. Validations with some :on option will only run in the specified context.

Check this documentation also as an official example.

like image 120
Arup Rakshit Avatar answered Nov 10 '22 00:11

Arup Rakshit


Context could really help you, but following maybe not.

validates_presence_of :name,: email, on: :special_context
validates_presence_of :name,:email, :password

This is because when you use validates_presence_of without specifying its context, it will be applied to all context(nil). Please see ref here So, maybe you could try as follow code:

validates_presence_of :name, :email, on: :special_context
validates_presence_of :name, :email, :password, on: [ :create, :update]
like image 32
GeekJ Avatar answered Nov 10 '22 00:11

GeekJ