问题描述
我正在从 rails 3.0.7 升级到 3.1,但无法通过我的测试.当我尝试在工厂中使用存根的活动资源对象时会出现问题.
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>
编辑
这不是工厂女孩的问题.如果我在控制台中执行以下操作,我会得到同样的错误.
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 )
一定与belongs_to如何映射id列有关.
It must be related to how belongs_to maps the id column.
推荐答案
我不喜欢猴子补丁,所以我创建了一个模块,我将在初始化时包含该模块以扩展 ActiveRecord
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 }
然后在每个 ActiveRecord 模型中看起来像:
Then in each ActiveRecord model would look like:
#task.rb
class Task < ActiveRecord::Base
ar_belongs_to :employee
end
希望这对某人有帮助
这篇关于rails 3.1.0belongs_to ActiveResource 不再工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!