2011-01-27 62 views
8

我看過http://railscasts.com/episodes/73-complex-forms-part-1http://railscasts.com/episodes/74-complex-forms-part-2,但它在嘗試代碼時似乎不適用於我 - 從那以後,我的假設在rails中發生了很多變化。第二個問題是我使用JQuery。在Rails 3中以嵌套模型形式動態添加字段

有誰知道任何在線教程可能會顯示一個更簡單的方法來做到這一點?我已經制作了一個嵌套的模型表單 - 所以它真的只是添加/刪除字段動態地部分那些殺死我。

+1

你能提供的如何沒有工作描述?導致您確定代碼無法正常工作的行爲是什麼? – 2011-01-27 01:08:29

+0

3.times {@ project.tasks.build}在我的視圖中看起來沒有任何影響 – Elliot 2011-01-27 01:16:08

回答

11

下面是一個簡單示例,顯示如何從單個頁面發出多個邀請。一些小細節丟失了,但它可能足以提供幫助。你可以通過一些簡單的jQuery添加和刪除視圖中的字段。此代碼可以適應任何種類的嵌套模型情況。希望能幫助到你! :)

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.') 
    }); 
});