Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <h3>ActiveRecord Join Tables</h3> <p><code>has_many :through</code> and <code>has_and_belongs_to_many</code> relationships function through a <em>join table</em>, which is an intermediate table that represents the relationship between other tables. Unlike a JOIN query, data is actually stored in a table.</p> <h3>Practical Differences</h3> <p>With <code>has_and_belongs_to_many</code>, you don't need a primary key, and you access the records through ActiveRecord relations rather than through an ActiveRecord model. You usually use HABTM when you want to link two models with a many-to-many relationship.</p> <p>You use a <code>has_many :through</code> relationship when you want to interact with the join table as a Rails model, complete with primary keys and the ability to add custom columns to the joined data. The latter is particularly important for data that is relevant to the joined rows, but doesn't really belong to the related models--for example, storing a calculated value derived from the fields in the joined row.</p> <h3>See Also</h3> <p>In <a href="http://guides.rubyonrails.org/association_basics.html#choosing-between-has_many-through-and-has_and_belongs_to_many" rel="noreferrer">A Guide to Active Record Associations</a>, the recommendation reads:</p> <blockquote> <p>The simplest rule of thumb is that you should set up a has_many :through relationship if you need to work with the relationship model as an independent entity. If you don’t need to do anything with the relationship model, it may be simpler to set up a has_and_belongs_to_many relationship (though you’ll need to remember to create the joining table in the database).</p> <p>You should use has_many :through if you need validations, callbacks, or extra attributes on the join model.</p> </blockquote>
    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.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      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