8bithero
8bithero

Reputation: 1609

Rails 3 validating multiple fields if unique field value exists

I have an Assignment model which has the following fields: :user_id, :company_id, :role_id

Each user can have multiple roles within a company but each company can only have one user with role_id == 5.

I would like to do something like below (obviously this does not work).

validates :company_id, :uniqueness => { :scope => :role_id => {:is => 5}, :message => "Only one owner is allowed." }

Is there a way to achieve this in a similar format to the above or will I need to create a custom validation macros?

If a custom validation is required how exactly would this be done and where is the 'correct' place to store this code if a new class needs to be created that inherits from ActiveModel::EachValidator? (Do I keep it in the same file or create a new file and possibly save it in /lib?)

Thanks in advance.

Upvotes: 0

Views: 862

Answers (2)

8bithero
8bithero

Reputation: 1609

Ok, I've come up with a solution but not quite sure if it's the 'rails way' of doing this or if it's just a hack-y workaround. Can someone please correct me on this?

I have done the following in my Association.rb file:

validate :owner_exists
.
..
...
protected
  def owner_exists
      errors.add(:role_id, " of owner already exists") if (role_id == 5 && Assignment.where('company_id = ? AND role_id = 5', company_id ).exists?)
  end

Upvotes: 0

Cristian Bica
Cristian Bica

Reputation: 4117

validates_uniqueness_of :user_id, :scope => :company_id, :if => Proc.new{|user| user.role_id == 5 }

Upvotes: 1

Related Questions