开发者

rails 3.1.0 belongs_to ActiveResource no longer working

开发者 https://www.devze.com 2023-04-01 16:07 出处:网络
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.

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
cl开发者_运维技巧ass 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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消