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 => 'user2@email.com') 
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?

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 => 'user2@email.com')
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.


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,


If I'm not mistaken, you're just trying to do this.

user = User.create(:username => 'usertwo', :email => 'user2@email.com') 
walmart = Store.create(:business_name => 'Walmart', :address => 'San Francisco, USA')

user.products.create(:name => 'Apple', :store => walmart)

Anything else required here that I'm not seeing?


Try doing this

store_1 = Store.new(:business_name => 'Test Store',
:address => 'Test Address',
:phone_number => '555-555-555')

store_1.id = 1
store_1.save!

The trick is not to set the id within the hash as it is protected.

Scott


What I did was update the particular products to a certain user, see this question:

Can I update all of my products to a specific user when seeding?


You could just create a series of insert satements for this "seed migration", including the record Id for each user, store, product etc. You might have to update database sequences after this approach.

Another approach Create the initial records in you Rails app, through the GUI / web. Then use something like Yaml-db. So you can dump the data to a yaml file. You can now edit that file (if necessary) and use that same file to seed another instance of the db with "rake db:load"

Either way.... You know the Ids will not be shifting around on you when these objects are created in the new db instance.

I'm sure there are other ways to do this... Probably better ones, even. Here is a link to a write-up I did a while back for using yaml_db to seed an oracle database http://davidbharrison.com/database_seeding_oracle


Try this:

User.destroy_all
Product.destroy_all

user = User.create!([{:username => 'usertwo', :email =>'user2@email.com'},
{:username => 'userthree', :email => user3@email.com}])

user.each_with_index do |obj, index|
  Product.create!([{ :product_name => 'product #{index}', :user_id => obj.id }])
end

The table would look like this:


Need Your Help

Parsing XML with nodes containing underscores

xml actionscript-3 flash identifier e4x

How do I parse an XML document that contains nodes where underscores exist?

removing parts of two strings of an array

php arrays string replace

I'm trying to remove two parts of two strings of an array which is output from ftp_nlist. I am working with CI. ALSO PLEASE NOTE THE MULTI SELECT LIST IN VIEW ARE BEING WORKED ON AND ARE NOT CORREC...