Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I seed a belongs_to association?

I would like to seed my Products and assign them to a specific User and Store.

Product.rb

class Product < ActiveRecord::Base

  belongs_to :user
  belongs_to :store

  def product_store=(id)
    self.store_id = id
  end
end

Note: Store belongs_to Business (:business_name)

Seed.rb

This is my basic setup:

user = User.create(:username => 'user', :email => '[email protected]') 
store = Store.create(:business_name => 'store', :address => 'Japan')

I attempted these but they did not work:

# This gives random ID's ranging from 1 to 4425!?
user.products.create([{:name => "Apple", :product_store => Store.find_by_address('San Francisco, USA')}])

# This gives me undefined method 'walmart'.
 user.store.products.create([ {:name => "Apple"} ])

Is there a way to set the ID's so I can associate my Products to a Store and User?


UPDATE -

I have tried the answers below and still came out unsuccessful. Does anyone know of another way to do this?

like image 527
LearningRoR Avatar asked Dec 18 '11 10:12

LearningRoR


2 Answers

Although it sounds like you found a workaround, the solution may be of interested to others.

From your original seeds.rb

user = User.create(:username => 'user', :email => '[email protected]')
store = Store.create(:business_name => 'store', :address => 'Japan')

Create the store

Store.create({
  user_id: user.id
  store_id: store.id
}, without_protection: true)

In the original code snipped "user" and "store" variables are declared. The code assigns user_id / store_id (the model columns inferred by the belongs_to relationship in the Store model) to the id values that are present in the "user" and "store" variables.

"without_protection: true" turns off bulk assignment protection on the id fields. This is perfectly acceptable in a seeds file but should be used with extreme caution when dealing with user provided data.

like image 110
denos Avatar answered Nov 03 '22 00:11

denos


Or alternatively create your stores.

Then extract the correct one e.g.

store = Store.find_by_business_name('Test Store')

and then create it based on that e.g.

store.products.create(:product_name => "Product Test", :price => '985.93')

This will then set the relationship id for you,

like image 37
Scott Avatar answered Nov 03 '22 00:11

Scott