(Rails) How to display child records (one-to-many)

2019-08-16 12:45发布

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

2条回答
The star\"
2楼-- · 2019-08-16 13:10

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%>
查看更多
对你真心纯属浪费
3楼-- · 2019-08-16 13:16

Check out these Railscasts about complex (nested) forms and formtastic:

查看更多
登录 后发表回答