Ruby on rails 通过关系名称自定义has\u many

Ruby on rails 通过关系名称自定义has\u many,ruby-on-rails,Ruby On Rails,我的应用程序中有以下模型: class Ingredient < ApplicationRecord has_many :recipe_ingredients has_many :recipes, through: :recipe_ingredients end class RecipeIngredient < ApplicationRecord belongs_to :recipe belongs_to :ingredient end class Recipe

我的应用程序中有以下模型:

class Ingredient < ApplicationRecord
  has_many :recipe_ingredients
  has_many :recipes, through: :recipe_ingredients
end

class RecipeIngredient < ApplicationRecord
  belongs_to :recipe
  belongs_to :ingredient
end

class Recipe < ApplicationRecord
  has_many :recipe_ingredients
  has_many :ingredients, through: :recipe_ingredients
end


类成分
但是配方模型已经有了一个同名的文本字段
配料
,因此此设置
有许多:配料,通过::配方配料
应该更改。
如何使用
source
as
,将
成分
的名称更改为其他名称(
成分
),使用
source
-您可以根据需要命名关联(在您的示例中,您提到了
成分
),然后指定源,如果模型为
recipe\u components
,而
关联为
:component


有很多:配料项目,来源::配料,通过::配方配料

使用
源代码
-您可以根据需要命名关联(在您的示例中,您提到了
成分项目
),然后指定源代码,如果模型为
recipe\u components
,而
关联为
:component


有很多:配料项目,来源::配料,通过::配方配料

您也可以尝试一下:

has_many :items, class_name: "Ingredient"

您也可以尝试一下:

has_many :items, class_name: "Ingredient"

这里的根本问题是定义配料模型和配料文本字段之间的区别。您在配料文本字段中存储了哪些未存储在配料模型中的内容?然后,您可能会问:“我需要文本字段吗?”我想答案是现在。然后,你可以说:“接受成分和成分之间有什么区别?它们需要是两种不同的模型吗?@benjessop是的,你几乎是对的,配料文本字段有自己的功能,所以问题是我应该保持原样。谢谢@Eyeslandic,这很简单,但我的大脑太差了:D这里的根本问题是定义配料模型和配料文本字段之间的区别。您在配料文本字段中存储了哪些未存储在配料模型中的内容?然后,您可能会问:“我需要文本字段吗?”我想答案是现在。然后,你可以说:“接受成分和成分之间有什么区别?它们需要是两种不同的模型吗?@benjessop是的,你几乎是对的,成分文本字段有自己的功能,所以问题是我应该保持原样。谢谢@Eyeslandic,这很简单,但我的大脑太差了:谢谢你教我的大脑,这很好用!谢谢你教我的大脑,这很好用!谢谢,让我试试!谢谢,让我试试!