正如我在 StackOverflow 上看到的另一个问题,我需要像这样嵌套 hm => t
= f.fields_for :memberships do |mem|
= mem.fields_for :organisation do |org|
.row
.span5.org_name
= org.input :name, :label => "<strong>Name of the Organization</strong>"
.span5
= mem.input :title, :label => "<strong>Title in the Organization</strong>"
.row
.span5
= mem.input :starting_year, :label => "<strong>Starting Year</strong>"
.span5
= mem.input :ending_year, :label => "<strong>Ending Year</strong>"
.row
.span10
= org.text_area :description, :label => "<strong>Description of Organisation</strong>"
= mem.link_to_remove "Remove this oranisation"
= f.link_to_add "Add an organisation", :memberships
但是使用 Ryan Bates 的插件,据我所知,与会员组织的关联并没有建立,所以我创建了一个像这样的新方法:
= f.link_to_add_hmt "Add an organisation", :organisation, :memberships
然后我几乎只是逐字复制了 Ryan Bates 的插件,添加了一个新参数,在下面添加了 2 行
def link_to_add_hmt(*args, &block)
options = args.extract_options!.symbolize_keys
association = args.pop
association_two = args.pop
options[:class] = [options[:class], "add_nested_fields"].compact.join(" ")
options["data-association"] = association
args << (options.delete(:href) || "javascript:void(0)")
args << options
@fields ||= {}
@template.after_nested_form(association) do
model_object = object.class.reflect_on_association(association).klass.new
model_object.send(:"build_#{association_two}")
output = %Q[<div id="#{association}_fields_blueprint" style="display: none">].html_safe
output << fields_for(association, model_object, :child_index => "new_#{association}", &@fields[association])
output.safe_concat('</div>')
output
end
@template.link_to(*args, &block)
end
查找对“association_two”的引用。这很好用!