ActiveModel :: MissingAttributeError:无法写入未知属性`book_id`

时间:2017-03-20 11:48:41

标签: ruby-on-rails ruby

我有这个问题,但不知道为什么。 我用生成器创建模型:

bin/rails generate model Book name:string author:string description:text cover:string
bin/rails generate model Episode name:string description:text art:string
ant other...

book.rb

class Book < ApplicationRecord
has_many :episodes
end

episode.rb

class Episode < ApplicationRecord
belongs_to :book
has_many :scenes
end

在控制台中我尝试:book.episodes << episode我遇到了错误:ActiveModel::MissingAttributeError: can't write unknown attribute "book_id" 我的schema.rb

ActiveRecord::Schema.define(version: 20170320111956) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
create_table "answers", force: :cascade do |t|
t.text     "text"
t.string   "next_scene"
t.string   "next_episode"
t.string   "voiceover"
t.integer  "end"
t.datetime "created_at",   null: false
t.datetime "updated_at",   null: false
end
create_table "books", force: :cascade do |t|
t.string   "name"
t.string   "author"
t.text     "description"
t.string   "cover"
t.datetime "created_at",  null: false
t.datetime "updated_at",  null: false
end
create_table "episodes", force: :cascade do |t|
t.string   "name"
t.text     "description"
t.string   "art"
t.datetime "created_at",  null: false
t.datetime "updated_at",  null: false
end
create_table "scenes", force: :cascade do |t|
t.string   "name"
t.text     "text"
t.integer  "choise"
t.string   "next_scene"
t.string   "next_episode"
t.string   "art"
t.string   "music"
t.string   "sound_fx"
t.string   "voiceover"
t.integer  "end"
t.datetime "created_at",   null: false
t.datetime "updated_at",   null: false
end
end

在架构中我没有id_book,但为什么?我也做db:migrate并再次出错。

1 个答案:

答案 0 :(得分:1)

默认情况下,Rails使用将primary命名为自动生成列id的约定。如果您希望指定其他主键,例如book_id,则可以执行以下操作:

class Book < ApplicationRecord
  self.primary_key = "book_id"
end