Setting an association attribute from another association

Skip to first unread message

Simone Carletti

Apr 20, 2013, 5:57:34 AM4/20/13
Hello list,

I'm trying to find a solution to this problem. I have a Resource model with the following relationships

Resource -> Domain -> User
Resource -> Contact -> User

And this is my declaration

  factory :certificate do
    association :domain
    association :contact

What I'd like to do, it to be able to specify the user for both associations to be the same. With the current declaration, when the associations are evaluated they result in two different users.

Ideally, I'd like to do something like this

  factory :certificate do
    association :domain
    association :contact, user_id: domain.user_id


  factory :certificate do
    user = ...
    association :domain, user_id:
    association :contact, user_id:

Any suggestion?

-- Simone

Carlos Chavez

Apr 27, 2013, 7:18:46 PM4/27/13
Hi Simone.

Its occurs to me that you can use after_build, for example:

after_build do |

    u = FactoryGirl.create(:user)
certificate.domain = FactoryGirl.create(:domain, user:u) = FactoryGirl.create(:contact, user:u)


Individuals over processes. Interactions over tools. Agile Rails training from thoughtbot, the makers of Clearance, Shoulda, & Factory Girl:
You received this message because you are subscribed to the "factory_girl" mailing list.
To post to this group, send email to
To unsubscribe from this group, send email to
For more options, visit this group at
You received this message because you are subscribed to the Google Groups "factory_girl" group.
To unsubscribe from this group and stop receiving emails from it, send an email to
For more options, visit

Carlos Chávez.
Reply all
Reply to author
0 new messages