Rails NoMethodError: undefined method `name' for "#<RecipeType:0x000055cd000b18a0>":String

Rails NoMethodError: undefined method `name' for "#<RecipeType:0x000055cd000b18a0>":String

我在使用 Active Records 进行挑战时遇到了麻烦,我阅读了文档,并看到了我重新制作和工作的 belongs_to 的其他示例,我不知道我在做什么当我尝试调用 recipe.recipe_type.name 时这里做错了我得到错误 Rails NoMethodError: undefined method `name' for "#":String

schema.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

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

add_reference :recipes, :recipe_type, foreign_key: true

因为您已经将 reference_type 引用添加到 ReferenceType。

所以最终的模式是:

ActiveRecord::Schema.define(version: 2020_03_26_013134) do

  create_table "recipe_types", force: :cascade do |t|
    t.string "name"
    t.integer "recipe_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["recipe_id"], name: "index_recipe_types_on_recipe_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"
    t.integer "recipe_type_id"
    t.index ["recipe_type_id"], name: "index_recipes_on_recipe_type_id"
  end
end

models/recipe_type

class RecipeType < ApplicationRecord
    has_many :recipes
end

models/recipe

class Recipe < ApplicationRecord
  belongs_to :recipe_type
end

你可以开始一个简单的has_many belongs_to active record association,我希望这能帮助到和帮助过我的人一样多的人,在这个旅程的开始,强烈推荐学习[= 25=、db:rollback、db:create 和 db:drop 给那些遇到麻烦的人。