Rail Model: Using validates_uniqueness_of with scope on attributes of associated entity?
I have Model defined as be开发者_JS百科low
class One <Active:Record:Base
{
has_and_belongs_to_many :twos, {:join_table => 'map__ones__twos'}
}
class Two <Active:Record:Base
{
has_and_belongs_to_many :ones, {:join_table => 'map__ones__twos'}
}
I want that name attribute of two should be unique for scope of one. That means all of twos belonging to one should have unique name. Here i can not specify some thing like below in Two model
validates_uniqueness_of :name, :scope => one_id
because on_id is not a column of twos table. Rather one_id and two_id are mapped to each other through table map_ones_twos (many to many relationship)
Please suggest
I have often found that using has_and_belongs_to_many is more trouble than it's worth. When I have many-to-many relationships, I create a join table and make a model for it. Then, the join model can have a validation on the uniqueness of the two ids.
Excuse the names. I am using the example table names from your question. In your case, this would look like:
class MapOnesTwo < ActiveRecord::Base
belongs_to :one
belongs_to :two
validates_presence_of :one_id, :two_id
validates_uniqueness_of :one_id, :scope => :two_id
end
Your One model looks like this:
class One < ActiveRecord::Base
has_many :ones_twos, :dependent => :destroy
has_many :twos, :through => :ones_twos
end
And your Two model looks like this:
class Two < ActiveRecord::Base
has_many :ones_twos, :dependent => :destroy
has_many :twos, :through => :ones_twos
end
精彩评论