无法在ActiveRecord调用中指定值(Ruby,Sinatra,而不是Rails)

时间:2015-09-10 03:17:37

标签: ruby activerecord sinatra sinatra-activerecord

我有一个名为Admin的Model对象的引用,它有一个名为id的字段。可以在puts行中访问object属性。我现在需要将该ID传递给ActiveRecord调用以创建另一个对象(它用作外键),如下所示,但它会抛出下面复制的异常(admin.id不会在Bill.create调用中被拾取) :

admin = Admin.find_by(email:email)
puts "admin id #{admin.id}"  # this gets printed with correct value  
bill = Bill.create(admin_id: admin.id, body: body)

异常

/usr/local/rvm/gems/ruby-2.2.1/gems/activerecord-4.2.4/lib/active_record/attribute_assignment.rb:59:in `rescue in _assign_attribute': unknown attribute 'admin_id' for Bill. (ActiveRecord::UnknownAttributeError)
        from /usr/local/rvm/gems/ruby-2.2.1/gems/activerecord-4.2.4/lib/active_record/attribute_assignment.rb:54:in `_assign_attribute'
        from /usr/local/rvm/gems/ruby-2.2.1/gems/activerecord-4.2.4/lib/active_record/attribute_assignment.rb:41:in `block in assign_attributes'
        from /usr/local/rvm/gems/ruby-2.2.1/gems/activerecord-4.2.4/lib/active_record/attribute_assignment.rb:35:in `each'
        from /usr/local/rvm/gems/ruby-2.2.1/gems/activerecord-4.2.4/lib/active_record/attribute_assignment.rb:35:in `assign_attributes'
        from /usr/local/rvm/gems/ruby-2.2.1/gems/activerecord-4.2.4/lib/active_record/core.rb:564:in `init_attributes'
        from /usr/local/rvm/gems/ruby-2.2.1/gems/activerecord-4.2.4/lib/active_record/core.rb:281:in `initialize'
        from /usr/local/rvm/gems/ruby-2.2.1/gems/activerecord-4.2.4/lib/active_record/inheritance.rb:61:in `new'
        from /usr/local/rvm/gems/ruby-2.2.1/gems/activerecord-4.2.4/lib/active_record/inheritance.rb:61:in `new'
        from /usr/local/rvm/gems/ruby-2.2.1/gems/activerecord-4.2.4/lib/active_record/persistence.rb:33:in `create'
        from test.rb:34:in `<main>'

Bills模型的ActiveRecord迁移

 def up
     create_table :bills do |t|
         t.integer :admin_id
         t.text :body
     end
    add_foreign_key :bills, :admins
  end

提前感谢您分享我所做错的见解。

1 个答案:

答案 0 :(得分:0)

根据我的评论,你应该把它变成belongs_to关系,这里是重构的迁移(使用最新的Rails 4语法):

class CreateBills < ActiveRecord::Migration
  def change
    create_table :bills do |t|
      t.references :admin
      t.text :body
    end
  end
end

将这些关系添加到模型中:

class Admin < ActiveRecord::Base
  has_many :bills
end

class Bill < ActiveRecord::Base
  belongs_to :admin
end

以及创建与管理员关联的帐单的代码:

admin = Admin.find_by(email:email)
puts "admin id #{admin.id}"  # this gets printed with correct value  
bill = admin.bills.create(body: body)