首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >获取ActiveModel::MissingAttributeError:同时使用ROR插入数据

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

Stack Overflow用户
提问于 2016-06-07 11:41:25
回答 1查看 117关注 0票数 0

在使用ROR通过rails控制台将数据插入数据库时,我得到了以下错误。

错误:

代码语言:javascript
复制
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'

在这里,我试图通过插入一些数据将一个表(注释)与另一个表(图书)链接起来。我的代码流如下:

代码语言:javascript
复制
irb(main):004:0>book=Book.find(1)
comment = Comment.new :text => "This is an comment", :author => "Adam"
book.comments << comment

.......create_comments.rb:

代码语言:javascript
复制
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:

代码语言:javascript
复制
class Book < ActiveRecord::Base
    has_many :comments
end

comment.rb:

代码语言:javascript
复制
class Comment < ActiveRecord::Base
    belongs_to :book
end

在执行最后一行时,会出现此错误。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-06-07 12:03:03

注释表中没有book_id列。

遵循以下步骤:

  1. rails g migration AddBookToComments book:references

它将创建一个迁移文件,如下所示:

代码语言:javascript
复制
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中的强参数中添加book_id

然后试着:

代码语言:javascript
复制
> book=Book.find(1)
> comment = book.comments.new(:text => "This is an comment", :author => "Adam")
> comment.save!
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37678406

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档