Ruby on rails - Rails3 with jquery 中的动态表单字段



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

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

<!-- layouts/application.rhtml -->
<%= javascript_include_tag :defaults %>
<!-- projects/new.rhtml -->
<div id="tasks">
  <%= render :partial => 'task', :collection => @project.tasks %>
</div>
<p><%= add_task_link "Add a task" %></p>
<!-- projects/_task.rhtml -->
<div class="task">
<% fields_for "project[task_attributes][]", task do |task_form| %>
  <p>
    Task: <%= task_form.text_field :name %>
    <%= link_to_function "remove", "$(this).up('.task').remove()" %>
  </p>
<% end %>
</div>
 # 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,并且使用过时的做法和旧的框架。 我会尽力帮助你。

layouts/application.erb

<%= javascript_include_tag :defaults %>

项目/新.erb

<div id="tasks">
  <%= render :partial => 'task', :collection => @project.tasks %>
</div>
<p><%= add_task_link "Add a task" %></p>

项目/_task.erb

<div class="task">
<!-- I think this part should still work -->
<%= fields_for "project[task_attributes][]", task do |task_form| %>
  <p>
    Task: <%= task_form.text_field :name %>
    <!-- We're going to be defining the click behavior with unobtrusive jQuery -->
    <%= link_to "remove", "#", :class => 'remove_task'
  </p>
<% end %>
</div>

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

public/javascripts/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的宝石(见 https://github.com/ryanb/nested_form),它可以为您处理其中的大部分问题。他还使用Prototype,jQuery和他的嵌套表单gem创建了复杂嵌套表单的示例;您可以在nested_forms页面上找到链接。

好东西!

相关内容

  • 没有找到相关文章

最新更新