问题
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
回答1:
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%>
回答2:
Check out these Railscasts about complex (nested) forms and formtastic:
Complex forms (part 1) (at least check this)
Formtastic (part 1)
- Formtatic (part 2)
来源:https://stackoverflow.com/questions/1992094/rails-how-to-display-child-records-one-to-many-in-their-parents-form