FactoryGirl 属于并具有 has_many 关联
我有三个类:
class User
has_and_belongs_to_many :accounts
end
class Account
has_and_belongs_to_many :users
end
class Idea
belongs_to :user
belongs_to :account
end
这些工厂:
FactoryGirl.define do
sequence :subdomain do |n|
"subdomain#{n}"
end
factory :account do
subdomain { FactoryGirl.generate(:subdomain) }
end
end
FactoryGirl.define do
sequence :email do |n|
"foo-#{n}@example.com"
end
sequence :name do |n|
"Test User #{n}"
end
factory :user do
name { FactoryGirl.generate(:name) }
email { FactoryGirl.generate(:email) }
password "secret"
after_create {|i| Factory(:account, :user_ids => [i.id])}
end
end
Factory.define :idea do |idea|
idea.title 'Lorem ipsum dolor'
idea.description 'Lorem ipsum dolor sit amet'
idea.sequence(:user_id) { |n| Factory(:user).id }
idea.sequence(:account_id) { |n| idea.user.accounts.first.id }
end
最后一个不起作用,并引发以下错误:
Failure/Error: idea = Factory :idea
NoMethodError:
undefined method `accounts' for #<FactoryGirl::Declaration::Implicit:0x007fcc6c370a60>
如何分解创意和关联用户的(其中一个)帐户之间的关联?
I have three classes:
class User
has_and_belongs_to_many :accounts
end
class Account
has_and_belongs_to_many :users
end
class Idea
belongs_to :user
belongs_to :account
end
And these factories:
FactoryGirl.define do
sequence :subdomain do |n|
"subdomain#{n}"
end
factory :account do
subdomain { FactoryGirl.generate(:subdomain) }
end
end
FactoryGirl.define do
sequence :email do |n|
"foo-#{n}@example.com"
end
sequence :name do |n|
"Test User #{n}"
end
factory :user do
name { FactoryGirl.generate(:name) }
email { FactoryGirl.generate(:email) }
password "secret"
after_create {|i| Factory(:account, :user_ids => [i.id])}
end
end
Factory.define :idea do |idea|
idea.title 'Lorem ipsum dolor'
idea.description 'Lorem ipsum dolor sit amet'
idea.sequence(:user_id) { |n| Factory(:user).id }
idea.sequence(:account_id) { |n| idea.user.accounts.first.id }
end
The last one doesn't work, and throws the following error:
Failure/Error: idea = Factory :idea
NoMethodError:
undefined method `accounts' for #<FactoryGirl::Declaration::Implicit:0x007fcc6c370a60>
How do I factor the association between the Idea and (one of the) accounts of the associated User?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论