Note that there are some explanatory texts on larger screens.

plurals
  1. POrailscast 197 how to: function add_fields
    primarykey
    data
    text
    <p>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.</p> <p>in <strong>javascript/application.js</strong></p> <pre><code>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)); } </code></pre> <p><strong>helper/application_helper.rb</strong></p> <pre><code>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 =&gt; "new_#{association}") do |builder| render(association.to_s.singularize + "_fields", :f =&gt; builder) end link_to_function(name, h("add_fields(this, \"#{association}\", \"#{escape_javascript(fields)}\")")) end end </code></pre> <p><strong>_questions_fields.html.rb</strong></p> <pre><code>&lt;div class="fields"&gt; &lt;p&gt; &lt;%= f.label :content, "Pregunta" %&gt; &lt;%= link_to_remove_fields "remover", f%&gt;&lt;br /&gt; &lt;%= f.text_area :content, :rows =&gt; 3 %&gt;&lt;br /&gt; &lt;/p&gt; &lt;p&gt; &lt;% f.fields_for :answers do |builder| %&gt; &lt;%= render 'answer_fields', :f =&gt; builder %&gt; &lt;% end %&gt; &lt;/p&gt; &lt;p&gt;&lt;%= link_to_add_fields "Agregar respuesta", f, :answers %&gt;&lt;/p&gt; &lt;/div&gt; </code></pre> <p><strong>_form.html.rb</strong></p> <pre><code>&lt;%= form_for @asurvey do |f| %&gt; &lt;%= f.label :name, "Nombre de encuesta" %&gt;&lt;br /&gt; &lt;%= f.text_field :name %&gt; &lt;/p&gt; &lt;%= f.fields_for :questions do |builder| %&gt; &lt;%= render 'question_fields', :f =&gt; builder %&gt; &lt;% end %&gt; &lt;p&gt;&lt;%= link_to_add_fields "Agregar pregunta", f, :questions %&gt; &lt;p&gt;&lt;%= f.submit "Crear" %&gt;&lt;/p&gt; &lt;% end %&gt; </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload