【问题标题】:How to use rails associations from Rails console?如何从 Rails 控制台使用 Rails 关联?
【发布时间】:2019-01-24 07:33:51
【问题描述】:

我有两个 Active Record,分别称为 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 '(' 

有人知道如何解决这个问题吗?提前致谢

【问题讨论】:

  • 使用这个Ingredient.create!(name: 'Glutein-free Bread', price: 0.2, category: Category.find_by(title: 'Bread Type').id)
  • 首先您必须找到类别,然后将其添加到您的成分中。

标签: ruby-on-rails ruby activerecord associations rails-console


【解决方案1】:

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

# 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

【讨论】:

    【解决方案2】:
    @category = Category.find_by(title: "Bread Type")
    @category.ingredients
    

    显示所有成分相关的类别,如果两个表之间存在关联,则使用它。

    现在,您可以创建成分相关的类别

    @category.ingredients.create!(name: "example", price: 202)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-18
      • 1970-01-01
      • 2017-09-30
      • 1970-01-01
      • 2021-10-16
      • 2016-11-30
      • 2021-10-19
      • 1970-01-01
      相关资源
      最近更新 更多