2011-06-23 34 views
0

作爲Ruby和Rails的新手,我不確定如何在標題中解釋這一點,所以我將在此處進行說明。我的目標是創建許多產品,並且每個提交只有一個整體位置。Rails爲此模型建立關係的方式

我有一個Product MVC和形式的快速醜陋的草圖會是這樣的:

總體定位

form_for @product 

<p> 
<%= f.label :location %>:<br> 
<%= f.text_field :location %> 
</p> 

產品一個

<p> 
<%= f.label :name %>:<br> 
<%= f.text_field :name %> 
<%= f.label :price %>:<br> 
<%= f.text_field :price %> 
</p> 

產品二(s AME)

<p> 
<%= f.label :name %>:<br> 
<%= f.text_field :name %> 
<%= f.label :price %>:<br> 
<%= f.text_field :price %> 
</p> 

產品三(下同)

<p> 
<%= f.label :name %>:<br> 
<%= f.text_field :name %> 
<%= f.label :price %>:<br> 
<%= f.text_field :price %> 
</p> 

<%= f.submit %> 
<% end %> 

你如何設定,讓所以當用戶在表單上創建3個產品這種關係可能發生,他只有一個他們所有3人的位置?

回答

2

這樣:

class Location < AR::Base 
    has_many :products 
end 

class Product < AR::Base 
    belongs_to :location 
end 

你會再建立一個嵌套的資源路徑:

resources :locations do 
    resources :products 
end 

而當你要添加一個位置,你可以將產品添加到它fields_for。

+0

的形式是的form_for @location呢?或者我可以保留@product並擁有上述模型和路線? – LearningRoR

+0

form_for @location,fields_for:產品 –

+0

謝謝你,這是一個偉大的方式來建立未來。 – LearningRoR

0

是使用nested_attributes_for在這種情況下它所需..

+0

這並不重要,你相信完成我的產品的最佳方式是什麼? – LearningRoR