我有一个名为 Pair 的模型,它有多个:问题,每个问题都有一个:答案。
我一直在关注这个关于创建嵌套表单的 railscast,但是我想在单击“添加问题”链接时同时生成一个问题字段和它的答案字段。
在遵循 railscast 之后,这就是我所拥有的:
..javascripts/common.js.coffee:
window.remove_fields = (link)->
$(link).closest(".question_remove").remove()
window.add_fields = (link, association, content)->
new_id = new Date().getTime()
regexp = new RegExp("new_" + association, "g")
$(link).before(content.replace(regexp, new_id))
application_helper.rb:
def link_to_add_fields(name, f, association)
new_object = f.object.class.reflect_on_association(association).klass.new
fields = f.simple_fields_for(association, new_object, :child_index => "new_#{association}") do |builder|
render(association.to_s.singularize + "_fields", :f => builder)
end
link_to_function(name, "window.add_fields(this, \"#{association}\", \"#{escape_javascript(fields)}\")", class: "btn btn-inverse")
end
意见/对/_form.html.erb:
<%= simple_form_for(@pair) do |f| %>
<div class="row">
<div class="well span4">
<%= f.input :sys_heading, label: "System Heading", placeholder: "required", input_html: { class: "span4" } %>
<%= f.input :heading, label: "User Heading", input_html: { class: "span4" } %>
<%= f.input :instructions, as: :text, input_html: { class: "span4 input_text" } %>
</div>
</div>
<%= f.simple_fields_for :questions do |builder| %>
<%= render 'question_fields', f: builder %>
<% end %>
<%= link_to_add_fields "<i class='icon-plus icon-white'></i> Add Another Question".html_safe, f, :questions %>
<%= f.button :submit, "Save Pair", class: "btn btn-success" %>
<% end %>
_question_fields.html.erb 部分:
<div class="question_remove">
<div class="row">
<div class="well span4">
<%= f.input :text, label: "Question", input_html: { class: "span4" }, placeholder: "your question...?" %>
<%= f.simple_fields_for :answer do |builder| %>
<%= render 'answer_fields', f: builder %>
<% end %>
</div>
</div>
</div>
_answer_fields.html.erb 部分:
<%= f.input :text, label: "Answer", input_html: { class: "span4" }, placeholder: "your answer" %>
<%= link_to_function "remove", "remove_fields(this)", class: "float-right" %>
我对 reflect_on_association 部分特别困惑,例如调用.new
那里如何创建关联?我通常需要使用.build
同样对于我使用的 has_one.build_answer
而不是answers.build
- 那么这对 jQuery 部分意味着什么?