How to create an association with a value lazy-evaluated from another association

30 views
Skip to first unread message

Simone Carletti

unread,
Dec 13, 2013, 6:12:48 AM12/13/13
to factor...@googlegroups.com
Hello,

Is it possible to use an association as the value for another association in a trait?

Let me describe a (simplified) example. I have 3 models

- User
- Forum (belongs_to :forum)
- Thread (belongs_to :forum, belongs_to :user)

Please note that Thread contains an user_id, it does not belong to User using Forum (at the time being, I can't change such constraint).

What I'd like to know, is if there a way to define a trait like the one

FactoryGirl.define do
  factory :thread do
    trait :with_forum do
      association :user
      # Lazy-evaluate the value of user to the previously created factory
      association :forum, user: user
    end
  end
end

What the trait is supposed to do is to create an user and associate it to the thread.
Then it should create a forum, but the user should be the same instance previously created.

There are mainly two reasons:
  1. The user associated with the forum is the same of the thread
  2. I don't want to create two user factories on cascade
Any idea? I tried to use the lazy evaluation, but no way to use it with associations.

Thanks,
-- Simone

Reply all
Reply to author
Forward
0 new messages