Rails3中带有jquery的动态表单字段

我正在使用#134的rialscasts作为指南。

我试图通过文本链接动态添加表单域。 在railscast中,他使用以下代码很好地实现了它:

   
'task', :collection => @project.tasks %>

Task:

# projects_helper.rb def add_task_link(name) link_to_function name do |page| page.insert_html :bottom, :tasks, :partial => 'task', :object => Task.new end end

projects_help.rb中的内容是我最感兴趣的。问题是他是通过原型来做​​到这一点的。 我正在寻找使用jquery(和rails3)的完全重复的实现。 你怎么看? 谢谢!

我要说 – 这是一个非常古老的railscast,并使用过时的做法和旧的框架。 我会尽力帮助你。

布局/ application.erb

 <%= javascript_include_tag :defaults %> 

项目/ new.erb

 
<%= render :partial => 'task', :collection => @project.tasks %>

<%= add_task_link "Add a task" %>

项目/ _task.erb

 
<%= fields_for "project[task_attributes][]", task do |task_form| %>

Task: <%= task_form.text_field :name %> <%= link_to "remove", "#", :class => 'remove_task'

<% end %>

projects_helper.rb

 def add_task_link(name) # This is a trick I picked up... if you don't feel like installing a # javascript templating engine, or something like Jammit, but still want # to render more than very simple html using JS, you can render a partial # into one of the data-attributes on the element. # # Using Jammit's JST abilities may be worthwhile if it's something you do # frequently though. link_to name, "#", "data-partial" => h(render(:partial => 'task', :object => Task.new)), :class => 'add_task' end 

公共/ Java脚本/ application.js中

 $(function(){ // Binds to the remove task link... $('.remove_task').live('click', function(e){ e.preventDefault(); $(this).parents('.task').remove(); }); // Add task link, note that the content we're appending // to the tasks list comes straight out of the data-partial // attribute that we defined in the link itself. $('.add_task').live('click', function(e){ e.preventDefault(); $('#tasks').append($(this).data('partial')); }); }); 

目前的RailsCasts / ASCIICasts是#196(参见http://asciicasts.com/episodes/196-nested-model-form-part-1 )和197,它们已针对Rails3进行了更新。

Ryan Bates还创建了一个名为nested_form的gem(请参阅https://github.com/ryanb/nested_form ),它可以为您处理大部分内容。 他还使用Prototype,jQuery和他的嵌套表单gem创建了复杂嵌套表单的示例; 您可以在nested_forms页面上找到链接。

好东西!