Question

I have 2 models, for example model_1 and model_2.
Model_1 has_many model_2.

For model_1 I have "new" and "create" actions and one view for create objects of both models.

In view I used "form_for" for object model_1 and "fields_for" for object model_2. With one object of model_2 everything is working properly.

But my problem is that I dont know how many objects of model_2 user wants to create. Maybe one or maybe 5. I want that the user could create objects with one view and not creating first model_1 object and then create model_2 objects.

How can I solve this problem?

Was it helpful?

Solution

What you're asking is perfectly plausible, and has been done before with these resources:

The bottom line way to do this is you need to append the new elements to your form using Javascript. This can then work with accepts_nested_attributes_for to submit the data as one element

We've done this before - the secret is to use child_index: Time.now.to_i, here's the code:


Controller

#app/controllers/model1_controller.rb
Class Model1Controller < ApplicationController
    def new
        @model1 = Model1.new
        @model1.build_model2
        respond_to do |format|
           format.html
           format.js { render "add_field" }
        end
    end
end

View

#app/views/model1/new.html.erb
<%= form_for @model1 do |f| %>
   <%= f.text_field :attribute %>
   <%= render partial: "fields_for", locals: { child_index: Time.now.to_i } %>
   <%= link_to "Add Field", model1_new_path, remote: true, id: "add_field" %>
   <%= f.submit %>
<% end %>

#app/views/model1/add_field.html.erb
<%= form_for @model1 do |f| %>
   <%= render partial: "fields_for", locals: { child_index: Time.now.to_i } %>
<% end %>

Javascript

#app/assets/javascripts/application.js
$("#add_field").on("ajax:success", function(data) {
    $("new_form").append(data); // VERY simplistic (can be improved upon request)
});

This will allow you to add as many fields as you wish. It's a simple version of what we have, but should help you. Of course, if you need any help / clarification, I can amend!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top