Rails 3.1.0 owned by ActiveResource no longer works

I am upgrading from rails 3.0.7 to 3.1, and I am having problems getting my tests. The problem occurs when I try to use the clipped active resource object in the 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 spec stubbing, the employee is working. A reference to an object with an in-depth employee 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 problem. I get the same error if I do the following in the console.

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

It should be related to how own_to displays the id column.

+6
source share
1 answer

I did not like the monkey patch, so I created a module that I will include during initialization for the ActiveRecord extension

 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 model ActiveRecord will look like this:

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

Hope this helps someone

+5
source

Source: https://habr.com/ru/post/896406/


All Articles