Rails NoMethodError: неопределенный метод `name 'для" # «: String - PullRequest
1 голос
/ 26 марта 2020

У меня были проблемы с вызовом Active Records, я прочитал документацию и увидел другие примеры с belongs_to, которые я переделал и работал, я больше не имею понятия о том, что я делаю здесь неправильно, когда Я пытаюсь вызвать recipe.recipe_type.name Я получаю сообщение об ошибке Rails NoMethodError: неопределенный метод `name 'для" # ": 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

Ответы [ 2 ]

2 голосов
/ 26 марта 2020

Вы, кажется, добавили ссылку recipe_type в неправильную таблицу. Ваша последняя миграция, вероятно, должна была быть

add_reference :recipes, :recipe_type, foreign_key: true

, поскольку, как она есть, вы добавили ссылку на reference_type в ReferenceType.

0 голосов
/ 27 марта 2020

Итак, окончательная схема была:

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 assign_to, я надеюсь, что это поможет многим людям, которые помогли мне, в начале этого путешествия настоятельно рекомендуем изучить db: migrate, db: rollback, db: create и db: drop. для тех, кто сталкивается с некоторыми проблемами.

...