开发者

Right way to force uniqueness on a join model? (has_many :through)

开发者 https://www.devze.com 2023-01-20 19:19 出处:网络
I have a parent/child relationship via our users table, with models as such: class User < ActiveRecord::Base

I have a parent/child relationship via our users table, with models as such:

class User < ActiveRecord::Base

  # Parents relationship
  has_many :children_parents, :class_name => "ParentsChild", :foreign_key => "child_id", :dependent => :destroy
  has_many :parents, :through => :children_parents

  # Children relatiopnship
  has_many :parents_children, :class_name => "ParentsChild", :foreign_key => "parent_id", :dependent => :destroy
  has_many :children, :through => :parents_children
  ...
end

And in parents_child.rb:

class ParentsChild < ActiveRecord::Base

  belongs_to :parent, :class_name => "User"
  belongs_to :child, :class_name => "User"

end

Right now, it is possible in our "add children" form (just using vanilla nested attributes) to add the same user as a child multiple times for parents. I am not sure what the 'right' way to go about forcing uniqueness in the ParentsChild relationship, although I am leaning towards a unique index on (parent_id, child_id) at the database layer (using a migration of course开发者_运维技巧).

I am sure I could also enforce uniqueness constraints in the UsersController::update method, but would prefer to avoid changing that code (right now it doesn't reference parents/children at all, thanks to nested attributes in the form/model) if possible. I am most concerned with making sure we use the "proper" solution. What is the 'right' or 'rails' way to do this?


Using has_many :through, you can specify :uniq as an option, like this:

  has_many :parents, :through => :children_parents, :uniq => true
0

精彩评论

暂无评论...
验证码 换一张
取 消