I’m going through the Agile Web Development with Rails tutorial. There are Products, LineItems, and Carts.
Product
class Product < ActiveRecord::Base
attr_accessible :description, :image_url, :price, :title
has_many :line_items
end
LineItem
class LineItem < ActiveRecord::Base
attr_accessible :cart_id, :product_id, :product
belongs_to :product
belongs_to :cart
end
Cart
class Cart < ActiveRecord::Base
has_many :line_items, dependent: :destroy
end
LineItemsController
class LineItemsController < ApplicationController
def create
@cart = current_cart
product = Product.find(params[:product_id])
@line_item = @cart.line_items.build(product: product)
....
end
my question is about the 3rd line in the create action above. I understand passing a product_id into line_items.build() but I don’t understand what passing an entire product does?
thanks,
mike
That will set the relation to the product (as in belongs_to product)
You could also just set the product_id by hand, but why would you. It is much simpler that way.
Active record understands the concept of relations – so it will do the setting of ids for you automatically.