8

I watched http://railscasts.com/episodes/73-complex-forms-part-1 and http://railscasts.com/episodes/74-complex-forms-part-2 but it didn't seem to work for me when trying the code - my assumption is a lot has changed within rails since then. The second issue is I'm using JQuery.

Does anyone know of any tutorials online that might show an easier way to do this? I've already made one nested model form - so its really just the adding/removing fields dynamically part thats killing me.

2
  • 1
    Can you provide a description of how it didn't work? What was the behavior that led you to determine the code wasn't working? Commented Jan 27, 2011 at 1:08
  • 3.times { @project.tasks.build } didn't seem to have any effect even with the code in my view Commented Jan 27, 2011 at 1:16

1 Answer 1

11

Here's a simple example that shows how to send out multiple invites from single page. Some little details are missing but it might be enough to help. You can add and remove fields from the view via some simple jQuery. This code could be adapted to any kind of nested model situation. Hope it helps! :)

InviteController.rb

class InviteController < ApplicationController
  def new
    @invites = Invite.new
  end

  def create
    @invites = User.new(params[:user]).invites
    if @user.update_attributes(params[:user])
      return redirect_to root_url, :notice => "Your invite(s) were successfully sent!"
    else
      render :action => :new
    end
  end
end

User.rb

class User < ActiveRecord::Base
  has_many :invites

  accepts_nested_attributes_for :invites
end

Invite.rb

class Invite < ActiveRecord::Base
  belongs_to :user
  after_create :send_invite

  private

  def send_invite
    # Send e-mail...
  end
end

new.html.erb

<% form_tag invites_path do %>
  <%= error_messages_for :object => @user.invites %>
  <ul id="invite-list">
    <%= render @invites %>
  </ul>
  <div>
    <%= submit_tag "Send Invite" %>
    <%= link_to "Add Another", "#add", :id => "add-another" %>
  </div>
<% end %>

_invite.html.erb

<%= fields_for "user[invites_attributes][]", invite do |i| %>
  <li>
    <%= link_to("Remove", "#delete", :class => "delete-invite") %>
    <%= i.label :full_name, "Full Name" %>
    <%= i.text_field :full_name %>
    <%= i.label :email, "Email Address" %>
    <%= i.text_field :email %>
  </li>
<% end %>

application.js

$(document).ready(function() {
  $('a#add-another').click(function() {
    $('#invite-list li:first').clone().find('input').val('')
    .end().appendTo('#invite-list');
  });

  $('.delete-invite').live('click', function() {
    if ($('#invite-list li').length > 1)
  $(this).parent().remove();
    else
  alert('You need at least one invite.')
  });
});
Sign up to request clarification or add additional context in comments.

4 Comments

Great! :) The only thing different about the code I posted and Ryan Bate's code is that my example is saving the new invite objects to an existing user(object). The code above would have to be tweaked if you wanted to for example, create a new to-do list object with nested to-do items. It shouldn't be that big of a change though to do that.
What to do if while I clone the fields they all have the name attribute set to snippet[examples_attributes][0][codes_attributes][0][comment] ... how can I 'INCREMENT' that 0 so the save action reads all the fields sets?
I think Mr_Nizzle has a point. The index of child elements will be carried forward to each clone, creating problems when you actually save the form. I think this can be fixed by replacing the index with a random number (like Javascript Time.to_i or something) but I'm not 100% sure.
To increment, you either have to use Javascript wizardry or use the form_builder methods

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.