获取ActiveModel :: MissingAttributeError:使用ROR插入数据时

时间:2016-06-07 11:41:26

标签: ruby ruby-on-rails-4 sqlite

使用ROR通过rails控制台将数据插入数据库时​​出现以下错误。

错误:

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'

这里我试图通过插入一些数据来链接一个表(注释)和另一个表(书籍)。我正在解释下面的代码流程。

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

当我执行最后一行时,此错误即将发生。

1 个答案:

答案 0 :(得分:1)

您的评论表中没有book_id列。

按照以下步骤操作:

  1. rails g migration AddBookToComments book:references
  2. 将创建一个迁移文件:

    class AddBookToComments < ActiveRecord::Migration
      def change
        add_reference :comments, :book, index: true, foreign_key: true
      end
    end
    
    1. 运行rake db:migrate
    2. comments_controller.rb
    3. 中的强参数中添加book_id

      然后尝试:

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