Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails 3.1.0 belongs_to ActiveResource no longer working

I am upgrading from rails 3.0.7 to 3.1 and am having trouble getting my tests to pass. The problem occurs when I try to use a stubbed active resource object in a factory.

#employee.rb   
class Employee < ActiveResource::Base; end

#task.rb
class Task < ActiveRecord::Base
  belongs_to :employee
end

#factories.rb
Factory.define :employee do |e|
  e.name "name"
end

Factory.define :task do |t|
  t.employee { Factory.stub(:employee) }
end

On the console and in the spec stubbing an employee works. Referencing the stubbed employee object in a new task gives the following error.

Factory.create( :task, :employee => Factory.stub(:employee) )   

NoMethodError:
   undefined method `[]' for #<Employee:0x007fc06b1c7798> 

EDIT

This is not a factory girl issue. I get the same error if I do the following in the console.

Task.new( :employee => Employee.first )

It must be related to how belongs_to maps the id column.

like image 445
Aaron Renoir Avatar asked Sep 01 '11 12:09

Aaron Renoir


1 Answers

I didn't like the monkey patch so I created a module that I will include at initialization to extend ActiveRecord

module BelongsToActiveResource

    def self.included(base)
      base.extend(ClassMethods)
    end

    module ClassMethods

    def ar_belongs_to( name, options = {} )
      class_eval %(
        def #{name}
          @#{name} ||= #{options[:class_name] || name.to_s.classify }.find( #{options[:foreign_key] || name.to_s + "_id" } )
        end

        def #{name}=(obj)
          @#{name} ||= obj
          self.#{ options[:foreign_key] || name.to_s + "_id" } = @#{name}.#{ options[:primary_key ] || 'id' }
        end
      )
    end

  end

end   

ActiveRecord::Base.class_eval { include BelongsToActiveResource }

Then in each ActiveRecord model would look like:

 #task.rb
 class Task < ActiveRecord::Base
   ar_belongs_to :employee
 end

Hope this helps someone

like image 138
Aaron Renoir Avatar answered Nov 15 '22 12:11

Aaron Renoir