Anar
Anar

Reputation: 925

How can I implement appending new item in an item list dynamically?

I have one form in view for the @item_list:

<%= form_for @item_list do |f|%>
   some meta-info to describe item_list
<%end%>

and also I have a render partial called _item.html.erb:

<%= form_for @item_list.item do |f|%>
   some meta-info to describe item_list.item
<%end%>

In my index view, I have a button called add item, which will call a jquery ajax function to append this partial to a div block, and another button called done, which I expect to store all the info in all the forms at one time.

When I try to save these, the parameter doesn't include the item information. I guess that is because I didn't update the item_list at the backend when I tried to add a new item. I hope you can provide me some ideas on this.

Upvotes: 0

Views: 281

Answers (1)

agmin
agmin

Reputation: 9378

You're going to want to setup a nested form for this. There are many other questions on stackoverflow about nested forms, but here's the gist:

  • Create a new empty object in your controller to populate an item @item_list.items.build assuming an ItemList has_many Items
  • Add accepts_nested_attributes_for :item in your Item model
  • Add attr_accessible :items_attributes in your Item model as well
  • You're going to need to pass your form builder to the partial, so something like this:

    _form.html.erb
    
    <%= form_for @item_list do |f| %>
      <% @item_list.items.each do |item| %>
         <%= render 'item', :f => f %>
      <% end %>
    <% end %>
    
    _item.html.erb
    
    <%= f.fields_for :items, item do |item_form| %>
        <%= item_form.text_field ... %>
    <% end %>
    

If you need more specifics, please provide us with some more code, including your models with relationships. I'll leave the javascript to you at this point.

Upvotes: 3

Related Questions