简体   繁体   中英

Do I need a join table for a has_many :through association?

I've only created a has_and_belongs_to_many association before and it is different from has_many :through. For a has_many :through association, do I need a join table? How does the actual association work? Do I need an index? I can't find a great tutorial on this, any suggestions?

Yes you need the join table. This shows how: http://railscasts.com/episodes/47-two-many-to-many

This may also be helpful; has_many :through questions

By the way if you need to search with condition this will help: Has many through associations with conditions

Also a great example with code of editing the nested attributes of the join table at Rails nested form with has_many :through, how to edit attributes of join model? .

All these are sorts of things you might find yourself wanting to do :)

Index are optional and also vary by db. mySQL used to only support 1 at a time. Not sure if that has changed.

It depends on how you want to use the has_many :through relation. There are two different cases (named in the guide to relations

  1. for an n:m relation: the example in the guide is physicians have appointments with patients.
  2. for an 1:n and an additional 1:n relation: the example in the guide is 1 document has many sections and 1 section has many paragraphs.

For the first one, you need the join table, you don't need the index. For the second one, you need none of them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM