ruby-on-rails - Rails NoMethodError:未定义的方法“名称”用于“#“:细绳
问题描述
我在挑战 Active Records 时遇到了麻烦,我阅读了文档,并看到belongs_to
了我重新制作和工作的其他示例,当我尝试调用 recipe 时,我不再知道我在这里做错了什么。 recipe_type.name 我收到错误 Rails NoMethodError: undefined method `name' for "#":String
架构.rb
create_table "recipe_types", force: :cascade do |t|
t.string "name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "recipe_type_id"
t.index ["recipe_type_id"], name: "index_recipe_types_on_recipe_type_id"
end
create_table "recipes", force: :cascade do |t|
t.string "title"
t.string "cuisine"
t.string "difficulty"
t.integer "cook_time"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.text "ingredients"
t.text "cook_method"
end
end
迁移
def change
create_table :recipes do |t|
t.string :title
t.string :cuisine
t.string :difficulty
t.integer :cook_time
t.timestamps
end
end
end
class AddFieldsToRecipe < ActiveRecord::Migration[5.2]
def change
add_column :recipes, :ingredients, :text
add_column :recipes, :cook_method, :text
end
end
class CreateRecipeTypes < ActiveRecord::Migration[5.2]
def change
create_table :recipe_types do |t|
t.string :name
t.timestamps
end
end
end
class AddRecipeRefToRecipeType < ActiveRecord::Migration[5.2]
def change
add_reference :recipe_types, :recipe_type, foreign_key: true
end
end
解决方案
您似乎添加了recipe_type
对错误表的引用。您的最后一次迁移可能应该是
add_reference :recipes, :recipe_type, foreign_key: true
因为实际上,您已将 reference_type 引用添加到 ReferenceType。
推荐阅读
- typescript - 如何在不使用 TypeScript 的情况下将类型添加到适用于任何对象键的函数?
- java - Understanding Exception tests in JUnit 5
- angularjs - 如何在 Jasmine 中模拟外部枚举设置
- elasticsearch - 如何从 Elasticsearch 中获取过滤选项
- tinymce - 如何在单击按钮时将 tinymce 内容重置为默认值
- javascript - 下载多个 SFTP 文件时出现 NodeJS 错误“检测到可能的 EventEmitter 内存泄漏。添加了 11 个错误侦听器”
- visual-studio - 为什么我的项目没有被 Azure Devops Nuget Pack 任务打包
- appdynamics - AppDynamics 支持 Opentracing
- docker - 如何从 DockerHub 的所有镜像中知道哪个 docker 基础镜像是正确的?
- c# - IEnumerable
存储稍后调用的函数?