Basically, what I’m trying to do is to seed my database with a bunch of initial data for my web app. For example, there are a list of products that all have one product_type.
My seeds.rb has the following code:
ProductType.delete_all
ProductType.create(:name => 'Furniture')
Product.delete_all
Product.create(:name => 'Chair', :type_id => ProductType.first.id, :packaging => '2 for $20', :price_per => 0.1, :default_packaging_number => 2)
Now, my issue is that the ProductType.first.id is merely a placeholder. What I would really like to do is to put something like:
:type_id => ProductType.where(:name => "Furniture").id
The issue is that when I do this, I get returned a huge number (70247318042560) that is clearly not the id. The console also returns the warning
warning Object#id will be deprecated; use Object#object_id
When I use the .object_id at the end of the where statement, it still returns that same large and incorrect number.
How do I pull the id of the furniture ProductType from the database? Do I need to modify permissions or something to access it?
First:
When you call
ProductType.where()you’re getting an ActiveRecord Relation, which is basically an array of results, even if there’s only one record in that result set.Try calling
ProductType.where(...whatever...).first.idand see if that solves your problem.Second, a better way:
Just save the product to a local variable.
Make sure you use the right association name (I’m guessing type…).
NOTE ActiveRecord already makes use of the “Type” column for polymorphic and single-table-inheritance relationships. If you’re association is setup where your relationship between Products and ProductTypes is called “Type” then you may be creating a conflict, or you may risk a conflict in the future. It’s best to not use that as a column name.
Why not stick with the default? If
Product belongs_to ProductTypethen the default column name would beproduct_type_idA final alternative:
If you reset your DB when you seed (probably a good idea) then you don’t need to call
Product.delete_all, the db will already be empty.In that case you can just do
ProductType.find(1)— if you’ve just started creating records the ids will be 1, 2, 3 etc in the order you create them.Hope this helps, feel free to ask questions!