2010-01-02 22 views
0

我有一個包含不同種類的「產品」一「類別」表,所以我在category.rb創建此:(Rails)如何以父母的形式顯示子記錄(一對多)?

class Category < ActiveRecord::Base 
    has_many :products 
end 

而這product.rb:

class Product < ActiveRecord::Base 
    belongs_to :categories 
end 

我想知道我怎麼可以得到:類別的產品在產品/ new.html.erb

回答

3

編輯:簡化代碼

我建議你的U se Formtastic這將做到automatically for you。如果你想這樣做導軌無Formtastic,解決辦法是:

假設你正在使用的部分爲new.html.erbedit.html.erb,代碼將進入_form.html.erb

<%= f.label :category_id %><br /> 
<%= f.collection_select :category_id, Category.all, :id, :name%> 
+0

你需要確保'Product'模型有'category_id'場和'products'表有'category_id'列好。您可以在新項目中運行以下命令以查看代碼。 '腳本/生成腳手架產品名稱:字符串category_id:整數' – 2010-01-03 03:24:02

+0

我看到了,我在那裏添加了productId,它的工作原理,thx u。但它顯示的是實際的category_id而不是category_name。這是我的代碼: <%semantic_form_for @category do | f | %> <%= f.input:category,:include_blank => false%> <%= f.buttons%> <% end %> – DNB5brims 2010-01-03 03:27:02

+0

還有一個跟進,我用這個之後,驗證變成瘋了,我有幾個驗證在我的product.rb中,輸入一些數據後,它會根本沒有任何輸入。發生什麼事?我正在使用ruby腳本/生成遷移add_category_id_to_product category_id:整數 添加category_id。 – DNB5brims 2010-01-03 04:09:03

相關問題