如何在Factory Girl中创建具有has_many:through关系的关联? [英] How do I create an association with a has_many :through relationship in Factory Girl?
本文介绍了如何在Factory Girl中创建具有has_many:through关系的关联?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我的模型中,我具有以下设置:
In my models I have the following setup:
class User < ActiveRecord::Base
has_many :assignments
has_many :roles, :through => :assignments
end
class Role < ActiveRecord::Base
has_many :assignments
has_many :users, :through => :assignments
end
class Assignment < ActiveRecord::Base
belongs_to :user
belongs_to :role
attr_accessible :role_id, :user_id
end
在我的factory.rb文件中,我有:
In my factory.rb file I have:
FactoryGirl.define do
factory :user do
sequence(:username) { |n| "user#{n}" }
email { "#{username}@example.com" }
password 'secret'
password_confirmation 'secret'
factory :admin do
...
end
end
factory :role do
name 'Normal'
value 'normal'
end
factory :assignment do
...
end
end
我正在努力找出如何在用户"块内的管理员"工厂中添加:name =>"admin",:value =>"admin"的角色,以便我可以调用
I'm struggling to figure out how I would add a role with, :name => "admin", :value => "admin", to the "admin" factory inside the "user" block so I can call
create(:admin)
在我的测试中,并且有一个具有管理员角色的用户.
in my tests and have a user with the admin role.
谢谢您的光临.
推荐答案
对于这样的工厂,您需要使用factory girl的回调. 试试这个:
For such a factory you need to use callbacks of factory girl. Try this:
FactoryGirl.define do
factory :user do
...
end
factory :admin, :parent => :user do
after_create {|u| Factory(:assignment, :role => Factory(:role, :name => 'admin', :value => 'admin'), :user => u)}
end
factory :role do
...
end
factory :assignment do
user {|a| a.association(:user)}
role {|a| a.association(:role)}
end
end
这篇关于如何在Factory Girl中创建具有has_many:through关系的关联?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文