Search code examples
rubyruby-on-rails-4sqlite

Getting ActiveModel::MissingAttributeError: while inserting data using ROR


I am getting the following error while inserting the data into database through rails console using ROR.

Error:

irb(main):004:0> book.comments << comment
   (1.0ms)  begin transaction
   (0.0ms)  rollback transaction
ActiveModel::MissingAttributeError: can't write unknown attribute `book_id`
        from C:/RailsInstaller/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/activerecord-4
.2.5.1/lib/active_record/attribute.rb:138:in `with_value_from_database'
        from C:/RailsInstaller/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/activerecord-4
.2.5.1/lib/active_record/attribute_set.rb:39:in `write_from_user'
        from C:/RailsInstaller/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/activerecord-4
.2.5.1/lib/active_record/attribute_methods/write.rb:74:in `write_attribute_with_
type_cast'

Here I am trying to link one table (comments) with another table (books) by inserting some data. My code flow is below:

irb(main):004:0>book=Book.find(1)
comment = Comment.new :text => "This is an comment", :author => "Adam"
book.comments << comment

.......create_comments.rb:

class CreateComments < ActiveRecord::Migration
  def change
    create_table :comments do |t|
      t.text :text
      t.string :author
      t.timestamps null: false
    end
  end
end

book.rb:

class Book < ActiveRecord::Base
    has_many :comments
end

comment.rb:

class Comment < ActiveRecord::Base
    belongs_to :book
end

While I am executing the last line this error is coming.


Solution

  • You have not book_id column in your comments table.

    Follow this below steps:

    1. rails g migration AddBookToComments book:references

    which will create a migration file as:

    class AddBookToComments < ActiveRecord::Migration
      def change
        add_reference :comments, :book, index: true, foreign_key: true
      end
    end
    
    1. run rake db:migrate
    2. add book_id in strong paremeters in comments_controller.rb

    Then try:

    > book=Book.find(1)
    > comment = book.comments.new(:text => "This is an comment", :author => "Adam")
    > comment.save!