0
我遵循railscast 197,但我使用rails 3.1.3,jquery和腳手架,沒有漂亮:腳手架,一切工作正常,但我不能添加字段,在該集中瑞安貝茨給代碼爲jquery,但不是爲我工作,這是我的代碼...先謝謝了。railscast 197如何:函數add_fields
在 的javascript/的application.js
function remove_fields(link) {
$(link).prev("input[type=hidden]").val("1");
$(link).closest(".fields").hide();
}
function add_fields(link, association, content) {
var new_id = new Date().getTime();
var regexp = new RegExp("new_" + association, "g");
$(link).parent().before(content.replace(regexp, new_id));
}
助手/ application_helper.rb
module ApplicationHelper
def link_to_remove_fields(name, f)
f.hidden_field(:_destroy) + link_to_function(name, "remove_fields(this)")
end
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
end
_questions_fields.html.rb
<div class="fields">
<p>
<%= f.label :content, "Pregunta" %>
<%= link_to_remove_fields "remover", f%><br />
<%= f.text_area :content, :rows => 3 %><br />
</p>
<p>
<% f.fields_for :answers do |builder| %>
<%= render 'answer_fields', :f => builder %>
<% end %>
</p>
<p><%= link_to_add_fields "Agregar respuesta", f, :answers %></p>
</div>
_form.html.rb
<%= form_for @asurvey do |f| %>
<%= f.label :name, "Nombre de encuesta" %><br />
<%= f.text_field :name %>
</p>
<%= f.fields_for :questions do |builder| %>
<%= render 'question_fields', :f => builder %>
<% end %>
<p><%= link_to_add_fields "Agregar pregunta", f, :questions %>
<p><%= f.submit "Crear" %></p>
<% end %>