我使用rialscast#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)的完全重复的实现。你怎么看?谢谢!
答案 0 :(得分:14)
你要说的是 - 这是一个非常古老的railscast,并且正在使用过时的做法和旧的框架。我会尽力帮助你。
布局/ application.erb
<%= javascript_include_tag :defaults %>
项目/ new.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
公共/ Javascript角/ 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'));
});
});
答案 1 :(得分:5)
目前的RailsCasts / ASCIICasts是#196(见http://asciicasts.com/episodes/196-nested-model-form-part-1)&amp; 197已针对Rails3进行了更新。
Ryan Bates还创建了一个名为nested_form的宝石(参见https://github.com/ryanb/nested_form),它可以为您处理大部分内容。他还使用Prototype,jQuery和他的嵌套表单gem创建了复杂嵌套表单的示例;你可以在nested_forms页面上找到一个链接。
好东西!