[英]How to get FactoryGirl model attributes with has_and_belongs_to_many association?
[英]If and how to use the has_and_belongs_to_many association in ActiveRecord
嘗試創建一個域,用戶可以在其中創建咖啡和混合咖啡列表。 混合有很多咖啡,而咖啡有很多混合。 這是我到目前為止的內容:
class User < ActiveRecord::Base
has_many :roasts
has_many :blends, :through => :roasts
class Roast < ActiveRecord::Base
belongs_to :user
# TODO: associate roasts with blends
class Blend < ActiveRecord::Base
# TODO: associate blends with roasts
如何建立這種關系? 我需要某種聯接表嗎?
嗨! 我認為您可以像下面的代碼塊一樣定義關聯。
class User < ActiveRecord::Base
has_many :blend_and_roasts
has_many :blends, through: :blend_and_roasts
has_many :roasts, through: :blend_and_roasts
class Roast < ActiveRecord::Base
has_many :blend_and_roasts
has_many :blends, through: :blend_and_roasts
class Blend < ActiveRecord::Base
has_many :blend_and_roasts
has_many :roasts, through: :blend_and_roasts
編碼愉快!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.