How to build children of a nested form in the controller
I know how to build the 2nd object in a controller but how do you build a third or a fourth?
In my case i need to build 3.
Location - has_many :product_dates, :products
ProductDate - has_many :products & belongs_to :location
Product - belongs_to :location, :product_date
I build the Location and Product Date easily:
def new
@location = Location.new
@location.product_dates.build
end
Now i need to build the products on the form. Can anyone show me how to do this?
EDIT: Complete Answer:
def new
@location = Location.new
product_date = @location.product_dates.build
product_date.products.build
end
<%= form_for @location do |f| %>
<%= f.text_field :business %>
<%= f.t开发者_开发百科ext_field :address %>
<%= f.fields_for :product_dates do |date| %>
<%= date.date_select :date %>
<%= date.fields_for :products do |product| %>
<%= product.text_field :name %>
<%= product.text_field :price %>
<%= product.text_field :tag_list %>
<% end %>
<% end %>
<%= f.submit "Create" %>
<% end %>
You'll learn everything in video here.
EDIT:
change the nested part with:
<%= f.fields_for :product_dates do |date| %>
<%= date.date_select :date %>
<%= date.fields_for :products do |product| %>
<%= product.text_field :name %>
<%= product.text_field :price %>
<%= product.text_field :tag_list %>
<% end %>
<% end %>
Because products
are nested inside product_dates
add to your controller:
def new
@location = Location.new
@product_dates = @location.product_dates.build
@product = @product_dates.product.build
end
in you ProductDate model:
class ProductDate < ActiveRecord::Base
accepts_nested_attributes_for :products
...
in you Location model:
class Location < ActiveRecord::Base
accepts_nested_attributes_for :product_dates
...
And you form should be like this:
<% f.fields_for :product_dates do |date| %>
<%= date.text_field :content %>
<% date.fields_for :products do |product| %>
<%= product.text_field :content %>
<%end %>
<% end %>
精彩评论