Andy Bas
Andy Bas

Reputation: 217

Rails Model Validation to check the value of an attribute

I have a Project model and a User model. A project must have a client (User class) and so the Project model has a client_id foreign key.

The User model has a type attribute and will contain 3 if the user is a client.

I want to validate that when a project is assigned to a client, that @user.type is 3.

Project.rb

validates :client_id, presence: true, #@user.type must be 3
belongs_to :client, :class_name => User, :foreign_key => :client_id

User.rb

#constants
TYPES = {
    :manager => 1,
    :contractor => 2,
    :client => 3
}

Not to sure how to go about the validation. I read through the rails guide on validations but still can't seem to get a solution. Any ideas?

Upvotes: 3

Views: 2921

Answers (2)

Dty
Dty

Reputation: 12273

Use the inclusion validation helper. Docs here

Here's a quick example from the docs

class Coffee < ActiveRecord::Base
  validates :size, :inclusion => { :in => %w(small medium large),
    :message => "%{value} is not a valid size" }
end


EDIT:

Ok, I see what you mean. Don't use validation helpers for this, do it manually.

# somewhere in your model (don't be tempted to put this in your controller)
def assigning_client
  if @user.type == 3
    # do the assignment
  else
    errors.add(:base, :message => "User must be a client")
  end
end

The error will prevent the info from being saved as long as you use the bang version save! which forces validation.

Upvotes: 5

enriclluelles
enriclluelles

Reputation: 79

Just a pointer here. Don't use an attribute named type in your activerecord models. It conflicts with the way rails uses STI(Single Table Inheritance) as it uses the type attribute to determine the type of the class when its subclassing another

Upvotes: 2

Related Questions