Create a relationship between two objects

I have two models: (Albums and product)

1) Internal models

Inside album.rb:

class Album < ActiveRecord::Base attr_accessible :name has_many :products end 

Inside product.rb:

 class Product < ActiveRecord::Base attr_accessible :img, :name, :price, :quantity belongs_to :album end 

2) Using the " rails console ", how can I establish associations (so that I can use "<% = Product.first.album.name%>")?

eg.

 a = Album.create( :name => "My Album" ) p = Product.create( :name => "Shampoo X" ) # what next? how can i set the album and the product together? 
+7
source share
2 answers

You can do the following:

 a = Album.create( name: "My Album" ) p = Product.create( name: "Shampoo X" ) # OR p = Product.create( name: "Shampoo X", album_id: a.id ) # OR p.album = a # OR p.album_id = a.id # OR a.products << a # finish with a save of the object: p.save 

You may need to set the attribute available for album_id in the product model (not sure about this).

Check out @bdares comment as well.

+10
source

Add an association when creating the Product:

 a = Album.create( :name => "My Album" ) p = Product.create( :name => "Shampoo X", :album => a ) 
+2
source

All Articles