has_and_belongs_to_many vs has_many through

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

    Many of the answers clarify that you should use has_and_belongs_to_many vs. has_many through: if you will not need any extra data or validations on the join table.

    However, beware of taking this approach. In the early stages of application development, it is nearly impossible to know what extra features or validations you may need in the far future of your project's lifecycle. If you decided to use has_and_belongs_to_many, and want to add one simple datapoint or validation 2 years down the road, migrating this change will be extremely difficult and bug-prone. To be safe, default to has_many :through

提交回复
热议问题