我是 Rails 新手,有一个非常基本的问题。
在创建模型时,例如。我必须存储食谱及其步骤。现在我应该制作食谱表、步骤表和食谱步骤表,还是应该有食谱、步骤表并在食谱模型中定义 has_many :steps?
任何帮助都会很棒。
非常感谢
我是 Rails 新手,有一个非常基本的问题。
在创建模型时,例如。我必须存储食谱及其步骤。现在我应该制作食谱表、步骤表和食谱步骤表,还是应该有食谱、步骤表并在食谱模型中定义 has_many :steps?
任何帮助都会很棒。
非常感谢
您的数据库中始终需要有 3 个表。正如你所说recipes
steps
和recipe_steps
然后,您的模型有两个解决方案。第一个有 3 个模型:
class Recipe
has_many :recipe_steps
has_many :steps, through: :recipe_steps
end
class Step
has_many :recipe_steps
has_many :recipes, through: :recipe_steps
end
class RecipeStep
belongs_to :step
belongs_to :recipe
end
第二个只有两个模型:
class Recipe
has_and_belongs_to_many :steps
end
class Step
has_and_belongs_to_many :recipes
end
如果您不想管理recipe_steps
表中的数据,您将使用第二种解决方案。但是如果你想在这个表中添加一些信息(例如价格或数量),你必须使用第一个解决方案。
在所有情况下,您都必须创建 3 个表。
您可以在此处找到更多信息:http: //guides.rubyonrails.org/association_basics.html
我希望这有帮助