2012-10-02 22 views
0

從高級語言Java到使用非常簡潔的語法的RoR來說,大多數情況下都很容易,但我正在努力理解幕後發生的一些事情。Rails如何確定此ID的價值?

在下面的代碼中,Rails如何分配product_id:的值?無法使用product.id來代替?在此背景下,product_id:是什麼意思?它的價值從哪裏來?

在視圖:

<% @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 %> 

是不是因爲attr_accessible聲明我在line_items模型?:給了

class LineItem < ActiveRecord::Base 
    attr_accessible :cart_id, :product_id 
    belongs_to :product 
    belongs_to :cart 
end 
+0

Rails不是語言)) –

回答

1

實際上,belongs_to :product是什麼給你的模型(LineItem)這個屬性。因此,現在您可以通過執行LineItem.find(1).product_id來引用父產品(該LineItem屬於該產品),這將返回與LineItem.find(1).product.id相同的返回結果。

Rails使用此常規屬性(product_id),因爲它直接映射到表列。檢查你的schema.rb文件,你會發現它在line_items表內。

+0

感謝Agis;這就是我正在尋找的=) – kwikness

+1

LineItem.find(1).product_id將返回存儲在LineItem表中的產品的ID。因此,如果產品以某種方式從產品表中刪除LineItem.find(1).product.id將引發錯誤,因爲LineItem.product = nil和nil.id因此未定義(無法使用LineItem中指定的id檢索對象),所以它可以返回相同的結果,但不是所有情況下的結果 – jethroo

0

它會調用#to_param方法,它默認返回ID。

正如你來自Java的,我會說這是當你做System.out.println(anObject)其中隱含的調用#toString()方法

1

這可能意味着你有期望一個product_id的路線相似,而「加入購物車「鏈接鏈接到該路由的URL,並在該URL中傳遞product的ID。我相信line_items_path(product_id: product)與做line_items_path(product_id: product.id)是一樣的。

+0

此外,您可能有一個文件「app/controllers/line_items_controller.rb」,其中至少有一個操作處理「product_id」。該文件可能會比'LineItem'模型更多地告訴你。 –

+0

是的,我會在'line_items_controller.rb'中的'def create'下查看。這幾乎可以肯定,當「添加到購物車」鏈接正在被點擊時會發生什麼。也許你已經知道了。 –

0

product_idline_items_path路徑期望的參數。您可以傳遞一個對象而不是手動設置它:

line_items_path(product) 

結果應該是一樣的。如果您在路線中重命名它,它會破壞您的視圖,因此最好不要手動設置它。

0
line_items_path(product_id: product) 

是相當於

line_items_path(:product_id => product) 

這是一樣的

line_items_path({:product_id => product}) 

在這種特定的情況下product_id表現得像一個符號文本(通常你需要的領導:或%S [ ])。這種替代方法,在ruby 1.9中添加了更多類似json的散列語法。

+0

對不起,我們爲什麼不能寫'line_items_path(product.id)'而不是'line_items_path(product_id:product)'?因爲參數必須是散列? – Lamnk

+0

,因爲一般情況下,rails不知道你給它的id是指產品(取決於如何定義路由) –