lundi 24 août 2015

Dynamic forms and saving multiple instances of a Model using Rails

I have a form:

<%= form_for My_model.new do |f| -%>
    <div id="image-container">
        <%= image_tag("", id: "img") %>
    </div>

    <%= text_field_tag(:s_url) %>
    <%= text_field_tag(:image) %>

    <!-- Make dynamic not hardcoded -->
    <%= text_field_tag :num %><br />
    <%= text_field_tag :p_url %><br />

    <%= text_field_tag(:x_pos) %>
    <%= text_field_tag(:y_pos) %>

    <%= f.submit %>
<% end -%>

Which has s_url, image, num, p_url, x_pos, y_pos as inputs. I can currently save this as an instance of my_model with this controller:

def new
    @my_model = My_model.new
end

def create

    @my_model = My_model.new(s_url: params[:s_url], img: params[:image], num: params[:num], x: params[:x_pos], y: params[:y_pos], p_url: params[:p_url])
    if @urpic.save
      redirect_to some_index_path(@some_index, :anchor => params[:s_url])
    end
end

The user should be able to create multiple instances of the model simultaneously. Either with JavaScript or Rails, when pressing a button the form should add new fields, like this:

<%= form_for My_model.new do |f| -%>
    <div id="image-container">
        <%= image_tag("", id: "img") %>
    </div>

    <%= text_field_tag(:s_url) %>
    <%= text_field_tag(:image) %>

    <!-- Make dynamic not hardcoded -->
    <%= text_field_tag :num %><br />
    <%= text_field_tag :p_url %><br />

    <%= text_field_tag(:x_pos) %>
    <%= text_field_tag(:y_pos) %>

    <!-- 2nd instance -->
    <%= text_field_tag :num %><br />
    <%= text_field_tag :p_url %><br />

    <%= text_field_tag(:x_pos) %>
    <%= text_field_tag(:y_pos) %>

    <%= f.submit %>
<% end -%>

As you can see, every instance will use the same s_url and image, but differ in the other fields. On submit, all instances should be saved to the sqlite table, which I don't know how to implement in the My_modelController.

Aucun commentaire:

Enregistrer un commentaire