"无法写出未知属性"

时间:2014-12-18 14:01:38

标签: ruby-on-rails ruby

我按照教科书的说法运行,但发生了错误。  这是一本图书管理应用程序。

我想要投放什么

irb(main):001:0>publisher = Publisher.create name: 'Gihyo inc.', address: 'Ichigaya'
irb(main):002:0>publisher.books << Book.find(1)
irb(main):003:0>publisher.books.to_a

结果

首先,

irb(main):001:0>publisher = Publisher.create name: 'Gihyo inc.', address: 'Ichigaya'

似乎成功了。

接下来,

irb(main):002:0>publisher.books << Book.find(1)

失败。

结果如下。

 Book Load(0.6ms) SELECT "books".* FROM "books" WHERE "books"."id" = ? LIMIT 1 [["id", 1]]
  (4.0ms) begin transaction
  (0.3ms) rollback transaction
ActiveModel::MissingAttributeError: can't write unknown attribute `publisher_id'
   from ...

相关模型

book.rb

class Book < ActiveRecord::Base
 scope :costly, ->{where("price>?" ,3000) }

 belongs_to :publisher
end

publisher.rb

class Publisher < ActiveRecord::Base
 has_many :books
end

相关迁移

20141218113551_create_publishers.rb

class CreatePublishers < ActiveRecord ::Migration
 def change
  create_table :publishers do |t|
   t.string :name
   t.text :address

   t.timestamps
  end
 end
end

20141218113811_add_publisher_id_to_books.rb

class AddPublisherIdToBooks < ActiveRecord::Migration
 def change
  add_reference :books, :publisher, index: true
 end
end

有什么问题?

1 个答案:

答案 0 :(得分:0)

这实际上意味着数据库中没有此类字段。

检查您的迁移将有助于解决此问题。