0

I have a simple AR model:

class Purchaser < ActiveRecord::Base
  attr_accessor :name
  has_many :purchases

  def initialize(opts={})
    @name = opts[:name]
  end
end

In a rails runner script, when I try to create a new Purchaser, I'm getting a transaction error.

purchaser = Purchaser.find_or_create_by(
  name: "Foo"
)

Here is the error:

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'

What am I doing wrong? Ruby 2.1.2, PostgreSQL.

Justin Ramos
  • 116
  • 10

1 Answers1

2

You are overriding the initialize method in ActiveRecord. You should call super to execute the ActiveRecord (parent) constructor as well. You could do it after you execute your code. Something like:

def initialize(opts={})
   @name = opts[:name]
   super
end

Hope this helps.

Ron
  • 2,215
  • 3
  • 22
  • 30