Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create association between two instancied objects

I have two models: (Albums and Product)

1) Inside 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 "rails console", how can I set the associations (so I can use "<%= Product.first.album.name %>")?

e.g.

a = Album.create( :name => "My Album" )
p = Product.create( :name => "Shampoo X" )
# what's next? how can i set the album and the product together?
like image 867
rosary dextrose Avatar asked Dec 26 '12 00:12

rosary dextrose


2 Answers

You can do like this:

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 have to set the attribute accessible to album_id on the Product model (not sure about that).

Check @bdares' comment also.

like image 94
MrYoshiji Avatar answered Sep 25 '22 18:09

MrYoshiji


Add the association when you create the Product:

a = Album.create( :name => "My Album" )
p = Product.create( :name => "Shampoo X", :album => a )
like image 20
Ross Allen Avatar answered Sep 24 '22 18:09

Ross Allen