问题
I am following the railscast 197 but Im using rails 3.1.3,jquery and scaffold, no nifty:scaffold,everything works fine but I can't add fields, in that episode Ryan Bates give the code for jquery, but is not working for me, here is my code...thanks in advance.
in 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));
}
helper/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 %>
回答1:
I found the solution...here in stackoverflow this is:
link_to_function(name, h("add_fields(this, \"#{association}\", \"#escape_javascript(fields)}\")"))
My ex:
link_to_function(name, ("add_fields(this, #{association}', #{escape_javascript(fields)}')"))
of course this code in helpers/application_helper.rb
Yes, that is. Now it works. Thanks.
来源:https://stackoverflow.com/questions/9085866/railscast-197-how-to-function-add-fields