【问题标题】:If and how to use the has_and_belongs_to_many association in ActiveRecord如果以及如何在 ActiveRecord 中使用 has_and_belongs_to_many 关联
【发布时间】:2018-06-14 01:10:04
【问题描述】:

尝试创建一个域,用户可以在其中创建咖啡和混合咖啡列表。一种混合物有许多咖啡,一种咖啡有许多混合物。这是我目前所拥有的:

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

我如何建立这种关系?我需要某种连接表吗?

【问题讨论】:

    标签: ruby activerecord model-associations


    【解决方案1】:


    你好!我认为您可以像下面的代码块一样定义关联。

    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
    

    编码愉快!

    【讨论】:

    • @AlexSegers 你能告诉我数据库模式是如何定义的吗?
    • @AlexSegers 我编辑了答案,所以请检查你想要什么。 p.s 添加inverse_of 选项使应用程序更快,但我没有这样做,因为我想让答案更清楚
    猜你喜欢
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 2010-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多