(Rails)如何以父母的形式显示子记录(一对多)? [英] (Rails) How to display child records (one-to-many) in their parent's form?
问题描述
我有一个包含不同类型产品的类别表,所以我在category.rb中创建了这个表:
class Category< ActiveRecord :: Base
has_many:产品
结束
此产品。 rb:
class产品< ActiveRecord :: Base
belongs_to:categories
end
我想知道我怎么才能从products / new.html.erb中获取产品的类别:
编辑:简化代码 p>
我建议您使用 Formtastic ,它自动为你 。如果你想在没有Formtastic的情况下使用rails,解决方案是:
假设你对 new.html.erb
和 edit.html.erb
,代码将进入 _form.html.erb
<%= f.label:category_id%>< br />
<%= f.collection_select:category_id,Category.all,:id,:name%>
I have a "category" table that contains different kind of "product", so I create this in the category.rb:
class Category < ActiveRecord::Base
has_many :products
end
And this in product.rb:
class Product < ActiveRecord::Base
belongs_to :categories
end
I would like to know how can I get the :categories from the product in the products/new.html.erb
EDIT: Simplified code
I recommend that you use Formtastic which will do it automatically for you. If you want to do it rails without Formtastic, solution is:
Assuming you are using partial for new.html.erb
and edit.html.erb
, the code will go into _form.html.erb
<%= f.label :category_id %><br />
<%= f.collection_select :category_id, Category.all, :id, :name%>
这篇关于(Rails)如何以父母的形式显示子记录(一对多)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!