Note that there are some explanatory texts on larger screens.

plurals
  1. PORight way to force uniqueness on a join model? (has_many :through)
    primarykey
    data
    text
    <p>I have a parent/child relationship via our users table, with models as such:</p> <pre><code>class User &lt; ActiveRecord::Base # Parents relationship has_many :children_parents, :class_name =&gt; "ParentsChild", :foreign_key =&gt; "child_id", :dependent =&gt; :destroy has_many :parents, :through =&gt; :children_parents # Children relatiopnship has_many :parents_children, :class_name =&gt; "ParentsChild", :foreign_key =&gt; "parent_id", :dependent =&gt; :destroy has_many :children, :through =&gt; :parents_children ... end </code></pre> <p>And in parents_child.rb:</p> <pre><code>class ParentsChild &lt; ActiveRecord::Base belongs_to :parent, :class_name =&gt; "User" belongs_to :child, :class_name =&gt; "User" end </code></pre> <p>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 <code>(parent_id, child_id)</code> at the database layer (using a migration of course).</p> <p>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?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload