首先,一個念頭 - 大部分時間,產品有很多種類,但每個類別還含有多種產品。也許你的社團應該是多對多的?談談你的實際問題。
如果我理解正確,你的問題是關於如何創建數據庫中彼此相關的類別和產品,即如何在構建新類別時設置product_id
的值。
爲了清楚起見,如果您需要,product_id只能設爲類別。畢竟,該類別屬於該產品,因此必須保留其擁有者的ID。
所以,讓我們說,你想建立一個屬於現有產品的新類別 - 你可以這樣做:
# in your view, where you link from products/show.html.erb to category/new.html.erb
<%= link_to "Build new category for this product", new_category_url(:id => @product.id) %>
# you must have @product defined, and you also must have
# 'resources :categories' in your routes file
# in your controller action categories/new, set the new category's product id:
def new
@category = Category.new(:product_id => params[:id])
end
# include a hidden field to contain the product_id in your new form
<%= form_for @category do |f| %>
<%= f.hidden_field :product_id %>
... other fields, labels, etc.
<% end %>
# save the record as you normally would (analogous to the code in your comment to @Chowlett).
@category = Category.new(params[:category])
if @category.save
redirect_to :action => "list", :notice => "Category saved successfully."
else
render :action => "new"
end
上面的代碼可以讓你建立一個產品,然後每個類別一個接-一。因此,我們首先構建您的產品,然後包含從產品/展示頁面到您的類別/新表單的鏈接,並傳入您希望該類別參與的產品的ID。
如果你想在同一時間建立一個產品和一些類別,它有點複雜。欲瞭解更多信息,請看http://railscasts.com/episodes/196-nested-model-form-part-1(這是三部分系列的第一部分)和https://github.com/ryanb/nested_form。除非你對上述基礎知識非常滿意,否則我不建議採取這種行動。當我剛接觸Rails時,我曾經在這段代碼中陷入了一個星期!
非常感謝幫忙:)。 – user659068 2011-04-19 21:55:55
不客氣! :) – sscirrus 2011-04-19 22:52:11
偉大的答案!我有兩個部分的問題,這完美地回答了第一部分。如果你有一分鐘,你會介意在我的問題的第二部分發現[這裏]裂縫(http://stackoverflow.com/questions/5813528/how-to-pass-foreign-key-attributes-down-通一個嵌套外形在護欄-3)?它只能用嵌套的形式來處理這個問題。 – FattRyan 2011-04-28 06:39:28