Flo Rahl
Flo Rahl

Reputation: 1054

FactoryGirl association with reference

I have four models: User, Product, Ownership and Location. Userand Product have one Location, and Location belongs to User and to Product (Polymorphic model).

I want to use FactoryGirl to create products that have the same location as their owner.

factory :location do
  sequence(:address) { |n| "#{n}, street, city" }
end

factory :user do
  sequence(:name)  { |n| "Robot #{n}" }
  sequence(:email) { |n| "numero#{n}@robots.com"}
  association :location, factory: :location
end

factory :product do
  sequence(:name) { |n| "Objet #{n}" }
  association :location, factory: :location
end

factory :ownership do
  association :user, factory: :user
  association :product, factory: :product
end

I created a method in the product model file to retrieve the product's owner just by doing product.owner.

I want to adapt the product factory in order to replace the factoried location by product.owner.location. How can I do that?

EDIT 1

I want to use it like that:

First I create a user

FactoryGirl.create(:user)

Later I create a product

FactoryGirl.create(:product)

When I associate both of them

FactoryGirl.create(:current_ownership, product: product, user: user)

I want that the location of my product becomes the one of his owner.

Upvotes: 10

Views: 12874

Answers (2)

victorjtfranco
victorjtfranco

Reputation: 173

using an after_create callback should do the trick

factory :ownership do
  user # BONUS - as association and factory have the same name, save typing =)
  product
  after(:create) { |ownership| ownership.product.location = ownership.user.location }
end

Upvotes: 2

jvnill
jvnill

Reputation: 29599

use the following code.

factory :user do
  sequence(:name)  { |n| "Robot #{n}" }
  sequence(:email) { |n| "numero#{n}@robots.com"}
  association :location, factory: :location

  factory :user_with_product do
    after(:create) do |user|
      create(:product, location: user.location)
    end
  end
end

To create the records, just use the user_with_product factory.

UPDATE:

In response to your question update, you can add an after(:create) callback to the ownership factory

factory :ownership do
  association :user, factory: :user
  association :product, factory: :product

  after(:create) do |ownership|
    # update ownership.user.location here with ownership.user.product
  end
end

The problem with this is your current association setup. Since location belongs to user or product, the foreign key is in location. so a location can't both belong to a user and a product at the same time.

Upvotes: 11

Related Questions