DNB5brims
DNB5brims

Reputation: 30558

(Rails) How to display child records (one-to-many) in their parent's form?

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

Upvotes: 0

Views: 553

Answers (2)

makevoid
makevoid

Reputation: 3287

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

Upvotes: 0

Chandra Patni
Chandra Patni

Reputation: 17577

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%>

Upvotes: 3

Related Questions