Validation in the model when doing update_attributes in Rails

1

I want to know how I would do a validation in my model for when the @ model.update_attributes (params) in my controller is called to return a possible error or false which seems to be the default returned by update_attributes.

Following the logic of fat models, I thought of putting the validation in the model as it would thin my controller.

The question is how to implement this in the model so that my controller only continues with @ model.update_attributes (params). And return false if validation does not pass.

Validation should happen only in the update.

    
asked by anonymous 28.03.2014 / 21:26

2 answers

2

Cassio, considering that you want to do this validation only in the update, you could do something like:

class Invoice < ActiveRecord::Base
  validate :active_customer, on: :update

  def active_customer
    errors.add(:customer_id, "is not active") unless customer.active?
  end
end

You can see the documentation for this, here: link

    
01.04.2014 / 14:01
0

You can deploy Active Record Validations .

Example:

You have a model called User with the attributes :name , :email , :password , in it you can add the validations:

class User < ActiveRecord::Base
    validates :name, presence: true
    validates :password, length: { minimum: 5 }
    validates :email, presence: true
end

And then in your update method you can do the following:

def
    @user = User.find(params[:id])

    respond_to do |format|
        if @user.update_attributes(params[:user])
            format.html # index.html.erb
        else
            format.json { render json: @user.errors, status: :unprocessable_entity }
        end
    end
end

The @user.errors will display the validity errors.

I hope it helps:)

    
28.03.2014 / 22:18