问题
I have a form_for that creates a new 'Estimate' and each of these estimates can have an unlimited number of 'Items' (this is like a part number, but it will have it's own set of attributes). I would like to be able to create as many instances of the associated Items model as I want to before I submit the form that creates the new Estimate, and then have it create all of the associated Items that go with that Estimate.
I've read a lot in the API on form_for and accepts_nested_attributes_for, I've googled extensively, and I've watched the railscasts about nested model forms, and I've read through my rails 3 book, but I've yet to find a 'rails way' to create all of these new objects in one go from the same form. In the railscast, Ryan has something like this in the controller:
def new
@estimate = Estimate.new
3.times { @estimate.items.build }
end
However, I do not know how many items are going to be on each estimate. I'm also not sure which fields_for syntax I should be using in the view, but I do understand I'll probably have to use JavaScript to dynamically create new form fields.
Here is how my models are related:
class Estimate < ActiveRecord::Base
has_many :items
accepts_nested_attributes_for :items
end
and:
class Item < ActiveRecord::Base
belongs_to :estimates
end
So, any ideas? Like I said, I can make my app do this (I'll probably use a lot of AJAX), but I was hoping someone might have a prettier solution.
Thanks.
回答1:
??? your way is the best Rails Way. Perhaps you don't know to build a form for items? By Rails Guides or Rails API's, you can write following:
<%= form_for @estimate do |f| %>
<p>
<%= f.label :xxx %>
<%= f.text_field :xxx %>
</p>
<%= f.fields_for :items do |item_field| %>
<p>
<%= item_field.label :yyy %>
<%= item_field.text_field :yyy %>
</p>
<% end %>
<% end %>
And you can use the sooooo good Gem, 'nested_form'. see: https://github.com/ryanb/nested_form
来源:https://stackoverflow.com/questions/4936129/how-can-i-create-multiple-instances-of-an-assosiated-model-from-a-rails-3-form-f