has_and_belongs_to_many vs has_many through

前端 未结 6 1427
没有蜡笔的小新
没有蜡笔的小新 2020-11-28 03:47

Please explain the difference between has_and_belongs_to_many and has_many through relationship. When and where to use which one?

6条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-28 04:03

    As far as I can remember, has_and_belongs_to_many gives you a simple lookup table which references your two models.

    For example,

    Stories can belong to many categories. Categories can have many stories.

    Categories_Stories Table
    story_id | category_id
    

    has_many :through gives you a third model which can be used to store various other pieces of information which don't belong to either of the original models.

    For example

    Person can subscribe to many magazines. Magazines can have many subscribers.

    Thus, we can have a subscription model in the middle, which gives us a similar table to the earlier example, but with additional properties.

    Subscriptions Table
    person_id | magazine_id | subscription_type | subscription_length | subscription_date 
    

    And so on.

提交回复
热议问题