I run as my textbook says, but error occurs. It's a book management application.
What I want to run
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
result
First,
irb(main):001:0>publisher = Publisher.create name: 'Gihyo inc.', address: 'Ichigaya'
seems succeeded.
Next,
irb(main):002:0>publisher.books << Book.find(1)
failed.
The result is as follows.
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 ...
related models
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
related migrations
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
What is wrong?
I fixed this error after changing -
belongs_to :user, counter_cache: :true
to this - belongs_to :user, counter_cache: true
Notice the boolean, I was using as a symbol...which was totally incorrect.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With