在使用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
endbook.rb:
class Book < ActiveRecord::Base
has_many :comments
endcomment.rb:
class Comment < ActiveRecord::Base
belongs_to :book
end在执行最后一行时,会出现此错误。
发布于 2016-06-07 12:03:03
注释表中没有book_id列。
遵循以下步骤:
rails g migration AddBookToComments book:references它将创建一个迁移文件,如下所示:
class AddBookToComments < ActiveRecord::Migration
def change
add_reference :comments, :book, index: true, foreign_key: true
end
endrake db:migratebook_id然后试着:
> book=Book.find(1)
> comment = book.comments.new(:text => "This is an comment", :author => "Adam")
> comment.save!https://stackoverflow.com/questions/37678406
复制相似问题