如何从 Rails 控制台使用 rails 关联?
How to use rails associations from Rails console?
我有两个名为 Ingredients 和 Category 的 Active Records。我必须在 rails 控制台中执行以下命令,它在创建时在类别 Bread type 中添加了一个名为 Protein Bread 的新项目面包类型同时分类:
Ingredient.create!(name: 'Protein Bread', price: 2.5, categories:
[Category.new(title: 'Bread Type')])
现在我的问题是如何添加一个新元素,例如在面包类型类别中其名称为 无谷蛋白面包?我试过了:
Ingredient.create!(name: 'Glutein-free Bread', price: 0.2, category: Bread
Type)
但我收到一条错误消息:
SyntaxError: (irb):4: syntax error, unexpected tCONSTANT, expecting
keyword_do or '{' or '('
有人知道如何处理吗?提前致谢
为了更好的阅读,我认为最好先创建/查找类别,然后再创建成分
# if category name already created
@category = Category.find_by_title("Bread Type")
@category.ingredients.build(name: 'Glutein-free Bread', price: 0.2)
@category.ingredients.build(name: 'other_item_name', price: 0.0)
# if it's new name category
@category = Category.create("Other Type")
# you can continue same as above
@category = Category.find_by(title: "Bread Type")
@category.ingredients
这是显示所有成分相关的类别,如果两个表之间存在关联时使用。
现在,您可以创建与配料相关的类别
@category.ingredients.create!(name: "example", price: 202)
我有两个名为 Ingredients 和 Category 的 Active Records。我必须在 rails 控制台中执行以下命令,它在创建时在类别 Bread type 中添加了一个名为 Protein Bread 的新项目面包类型同时分类:
Ingredient.create!(name: 'Protein Bread', price: 2.5, categories:
[Category.new(title: 'Bread Type')])
现在我的问题是如何添加一个新元素,例如在面包类型类别中其名称为 无谷蛋白面包?我试过了:
Ingredient.create!(name: 'Glutein-free Bread', price: 0.2, category: Bread
Type)
但我收到一条错误消息:
SyntaxError: (irb):4: syntax error, unexpected tCONSTANT, expecting
keyword_do or '{' or '('
有人知道如何处理吗?提前致谢
为了更好的阅读,我认为最好先创建/查找类别,然后再创建成分
# if category name already created
@category = Category.find_by_title("Bread Type")
@category.ingredients.build(name: 'Glutein-free Bread', price: 0.2)
@category.ingredients.build(name: 'other_item_name', price: 0.0)
# if it's new name category
@category = Category.create("Other Type")
# you can continue same as above
@category = Category.find_by(title: "Bread Type")
@category.ingredients
这是显示所有成分相关的类别,如果两个表之间存在关联时使用。
现在,您可以创建与配料相关的类别
@category.ingredients.create!(name: "example", price: 202)