首页 > 解决方案 > 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

标签: ruby-on-railsrubyrails-activerecord

解决方案


您似乎添加了recipe_type对错误表的引用。您的最后一次迁移可能应该是

add_reference :recipes, :recipe_type, foreign_key: true

因为实际上,您已将 reference_type 引用添加到 ReferenceType。


推荐阅读