ruby-on-rails - 如何从 Rails 控制台使用 Rails 关联?
问题描述
我有两个名为Ingredients和Category的活动记录。我必须在 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 '('
有谁知道如何去做?提前致谢
解决方案
为了更好地阅读,我认为最好先创建/查找类别,然后再创建成分
# 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
推荐阅读
- .net - 如何在安装新版本的 Wix 安装程序之前强制完全卸载?
- wpf - 为什么 System.IO.Compression.ZipFile.ExtractToDirectory() 在 TeamCity 的 Artifact.zip 上抛出 InvalidDataException?
- php - 如何在php中按月份名称对多维数组进行排序
- angular - 错误 TS2365:运算符“>=”不能应用于类型“字符串”和“数字”。(角度)
- javascript - 如何检查单选按钮是否被选中?
- mysql - MySQL中复合唯一键的重复输入错误
- django - NGINX 不提供收集的静态文件
- oracle - SQL Developer 错误 ORA-04072 无效的触发器类型问题
- json - 如何在 Angular 应用程序中使用 JWT Token 获取角色名称?
- kotlin - 如何将 Gradle testImplementation testFixtures('com.bla:bla-bla:master_d171111') 转换为 Kotlin Gradle?