has_and_belongs_to_many vs has_many through

前端 未结 6 1436
没有蜡笔的小新
没有蜡笔的小新 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:00

    From http://guides.rubyonrails.org/association_basics.html#choosing-between-has-many-through-and-has-and-belongs-to-many

    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). You should use has_many :through if you need validations, callbacks, or extra attributes on the join model.

提交回复
热议问题