1

我已经从 RailsCasts 嵌套模型表单第 2 部分示例中创建了一个嵌套模型,并让它与 Rails 3 和 JQuery 一起使用。目前,用户可以创建一个新项目并单击一个链接以添加新任务,然后在每个新任务中单击一个链接,该链接将允许他们向每个任务添加新分配。这是创建新任务的链接(创建新任务的链接类似):

        <p><%= link_to_add_fields "Add task", f, :task %></p>

那指的是这个助手:

  def link_to_add_fields(name, f, association)
new_object = f.object.class.reflect_on_association(association).klass.new
fields = f.fields_for(association, new_object, :child_index => "new_#{association}") do |builder|
  render(association.to_s.singularize + "_fields", :f => builder)
end
link_to_function(name, h("add_fields(this, \"#{association}\", \"#{escape_javascript(fields)}\")"))end

它的工作原理如下:通过单击链接,通过 JQuery 添加 html,该 JQuery 显示任务名称的表单字段和允许用户向任务添加新分配的链接。

我想做的是让分配表单出现在任务名称字段旁边 - 这样用户就不需要单击其他链接来为每个任务添加新分配。当页面首次通过项目控制器加载时,我可以完成此操作:

    1.times do
   task = @product.tasks.build
   1.times { task.assignments.build}
end

但是,因为我使用 JQuery 添加和删除 HTML,所以在“添加”新任务时不会调用控制器并且不会构建表单。

有没有办法在创建新任务字段时自动(从任务部分内)“构建”嵌套分配字段?

这是用户单击表单中的“新任务”链接时创建的任务表单的部分内容:

<div class = "fields">
<%= f.label :name, "Task name"%>
<%= link_to_remove_fields "remove", f %><br />
<%= f.text_field :name %>



<% f.fields_for :assignments do |builder| %>
    <%= render 'assignment_fields', :f => builder %>
<% end %>

<p><%= link_to_add_fields "Add assignments", f, :assignments %></p>

4

2 回答 2

1

I have a similar situation and I am currently (like you) looking for a solution. From Rails 3 source I found:

activerecord/lib/active_record/nested_attributes.rb:

# === One-to-many
#
# Consider a member that has a number of posts:
#
#   class Member < ActiveRecord::Base
#     has_many :posts
#     accepts_nested_attributes_for :posts
#   end
#
# You can now set or update attributes on an associated post model through
# the attribute hash.
#
# For each hash that does _not_ have an <tt>id</tt> key a new record will
# be instantiated, unless the hash also contains a <tt>_destroy</tt> key
# that evaluates to +true+.

I hope this gives you ideas.

于 2011-01-14T04:39:28.437 回答
0

创建任务表单后,您可以使用 jQuery 模拟单击​​添加分配链接。这样你就完全不依赖 rails 控制器了。

after_create_handler = function() { $('assignment add link identifier').click() }
于 2013-04-18T15:42:41.400 回答