首页 > 解决方案 > 如何从 Rails 控制台使用 Rails 关联?

问题描述

我有两个名为IngredientsCategory的活动记录。我必须在 rails 控制台中执行以下命令,该命令在Bread type类别中添加了一个名为Protein Bread的新项目,同时创建了Bread Type类别:

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 '(' 

有谁知道如何去做?提前致谢

标签: ruby-on-railsrubyactiverecordassociationsrails-console

解决方案


为了更好地阅读,我认为最好先创建/查找类别,然后再创建成分

# 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

推荐阅读