Coming from Java, a highly explicit language, to RoR, which uses a very terse syntax, is easy for the most part, but I’m struggling to understand a few of the things that are going on behind the scenes.
In the code below, how does Rails assign product_id: a value? Couldn’t product.id be used instead? What does the product_id: mean exactly in this context? Where does its value come from?
In the view:
<% @products.each do |product| %>
<div class="entry">
<%= image_tag(product.image_url) %>
<h3><%= product.title %></h3>
<%= sanitize(product.description) %>
<div class="price_line">
<span class="price"><%= number_to_currency(product.price, unit: '$') %></span>
<%= button_to 'Add to Cart', line_items_path(product_id: product) %>
</div>
</div>
<% end %>
Is it because of the attr_accessible statements I gave in my line_items model?:
class LineItem < ActiveRecord::Base
attr_accessible :cart_id, :product_id
belongs_to :product
belongs_to :cart
end
Actually,
belongs_to :productis what gives your model (LineItem) this attribute. So now you can reference the parent product (that this LineItem belongs to), by doing for exampleLineItem.find(1).product_id, which would return the same as doingLineItem.find(1).product.id.Rails uses this conventional attribute (product_id) as it directly maps to the table column. Check your schema.rb file, you will find it there, inside the line_items table.