FactoryGirl 属于并具有 has_many 关联

发布于 2024-12-19 14:27:51 字数 1216 浏览 1 评论 0原文

我有三个类:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文