我有一个简单的AR模型:
class Purchaser < ActiveRecord::Base
attr_accessor :name
has_many :purchases
def initialize(opts={})
@name = opts[:name]
end
end
在rails runner脚本中,当我尝试创建一个新的购买者时,我收到了一个交易错误。
purchaser = Purchaser.find_or_create_by(
name: "Foo"
)
这是错误:
activerecord-4.2.0.beta1/lib/active_record/transactions.rb:373:in `clear_transaction_record_state': undefined method `[]' for nil:NilClass (NoMethodError)
from activerecord-4.2.0.beta1/lib/active_record/transactions.rb:304:in `ensure in rollback_active_record_state!'
from activerecord-4.2.0.beta1/lib/active_record/transactions.rb:304:in `rollback_active_record_state!'
from activerecord-4.2.0.beta1/lib/active_record/transactions.rb:283:in `save'
from activerecord-4.2.0.beta1/lib/active_record/persistence.rb:34:in `create'
from activerecord-4.2.0.beta1/lib/active_record/relation.rb:141:in `block in create'
from activerecord-4.2.0.beta1/lib/active_record/relation.rb:300:in `scoping'
from activerecord-4.2.0.beta1/lib/active_record/relation.rb:141:in `create'
from activerecord-4.2.0.beta1/lib/active_record/relation.rb:211:in `find_or_create_by'
from activerecord-4.2.0.beta1/lib/active_record/querying.rb:6:in `find_or_create_by'
我做错了什么? Ruby 2.1.2,PostgreSQL。
答案 0 :(得分:2)
您正在覆盖ActiveRecord中的initialize
方法。您也应该调用super
来执行ActiveRecord(父)构造函数。您可以在执行代码后执行此操作。类似的东西:
def initialize(opts={})
@name = opts[:name]
super
end
希望这有帮助。