0

campaign.rb

class Campaign < ActiveRecord::Base
  has_many :items
  accepts_nested_attributes_for :item
end

item.rb

class Item < ActiveRecord::Base
  belongs_to :campaign
end

Campaign has 2 attributes: title and description
Item has 1 attirubte: name

I'll try explain myself by words, I want to create a nested form where they user insert the campaign's name and description but he can insert more than just 1 item, he can insert a list of items (in particular there will be a "+" button that when clicked a new item row will appear and the user can insert items).
At the end all is send all together clicking just one submit button. How can I reach my goal with rails?

zer0uno
  • 7,521
  • 13
  • 57
  • 86

2 Answers2

0

A nice gem along with tutorial is available from ryanbates who is the author of railscasts.com site.You can use this and have a look at tutorial here

And also if you want to try manually use the fields_for while writing in the form like here and manage some jquery code for add or remove.

kanna
  • 366
  • 2
  • 19
0

I answered a question just yesterday. Here's the link: Rails accepts_nested_attributes_for with f.fields_for and AJAX

I'll write out how it works & provide some resources to help give you some more ideas:


How It Works

Loading associative fields into a form is done by using f.fields_for

You'll do it like this:

#app/views/campaigns/new.html.erb
<%= form_for @campaign do |f| %>
    <%= f.fields_for :items do |a| %>
        <%= a.text_field :information %>
    <% end %>
<% end %>

In order to get this to work, you have to build the associated ActiveRecord objects in the backend before you render the view, like this:

#app/controllers/campaigns_controller.rb
def new
    @campaign = Campaign.new
    @campaign.items.build
end

Adding Extra Fields Via Ajax

Adding extra fields with Ajax requires engineering a new solution to the issue

The way you do this is to take the f.fields_for text & put it into a partial. This partial can be called from the original view, as well as another view (which we can render through Ajax)

The Ajax part works by basically taking a request from your form (the ajax request), and then using another action in your controller to build a new ActiveRecord object & render another partial that will contain another form. This partial will then call the original f.fields_for partial, allowing you to render another field

Your Ajax can then extract the new field & append it to your page. The way you get around the id issue (keeping the IDs sequential & unique) is to employ the child_index method, and use Time.now.to_i to generate a timestamp

If you read my answer referenced at the top of this answer, all of this will make sense :)

Some great resources for this:

Community
  • 1
  • 1
Richard Peck
  • 76,116
  • 9
  • 93
  • 147