【问题标题】:Rails one-way 'has_many' associationRails 单向“has_many”关联
【发布时间】:2019-02-21 20:03:03
【问题描述】:

我正在尝试制作基于 Rails 的应用程序(我只是在学习 RoR),但我偶然发现了这个问题。

有两种模型:Recipe 和 Item(食品)。配方可以有零个(我们可以在添加项目之前创建配方)或多个项目。但特定的食品不应与任何食谱绑定。这就是为什么 'has_many' 和 'belongs_to' 对我不起作用的原因,因为后者不能满足这个要求。

如果我要在没有任何框架的情况下执行此操作,我可能会在配方表中放置一个“项目”列,其中包含项目索引列表。但我有一种预感,这不是在 RoR 中执行此操作的合适方法,因为 Rails 中有模型关联。 拜托,有人能给我一个想法吗?

【问题讨论】:

  • 听起来你想要RecipeItem 之间的多对多关系。如果是这样,您应该查看has_many :throughhas_and_belongs_to。我更喜欢前者,从不使用后者。但是很多人使用后者取得了巨大的成功。

标签: ruby-on-rails associations


【解决方案1】:

我通常不使用 has_and_belongs_to_many,但在您的情况下,它似乎适合。你可以这样使用它:

class Recipe
  has_and_belongs_to_many :items
end

class Item
  has_and_belongs_to_many :recipes
end

您也可以使用 has_many :through,但您必须创建第三个表才能将 Recipe 和 Item 表连接在一起。

class Recipe
  has_many :item_recipes
  has_many :items, through: :item_recipes
end

class ItemRecipes
  belongs_to :recipe
  belongs_to :item
end

class Item
  has_many :item_recipes
  has_many :recipes, through: :item_recipes
end

您可以在这里找到更多信息:Rails Associations

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多