Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Might have to wittle at this a little, I see a couple potential problems:</p> <pre><code>def sort_questions params[:questions_attributes].to_a.each_with_index do |id, index| question = Question.find(id) question.position = index + 1 question.save(:validate =&gt; false) end render :nothing =&gt; true end </code></pre> <p>As mentioned by @nodrog, it should be <code>params[:template][:questions_attributes]</code> . Currently <code>params[:questions_attributes]</code> returns <code>nil</code>, and <code>nil.to_a</code> is <code>[]</code>, so that loop never executes. Once it does, <code>id</code> in the loop will be something like:</p> <pre><code>[["0",{"content"=&gt;"What are you doing?",...}], ... ] </code></pre> <p>Passing that to <code>find</code> won't work. You could use a lesser-known syntax like:</p> <pre><code>params[:template][:questions_attributes].to_a.each_with_index do |(id, attrs), index| question = Question.find(id) question.position = index + 1 question.save(:validate =&gt; false) end </code></pre> <p>Next, hashes in 1.9 <em>are</em> sorted, but I wouldn't count on the round-trip from form elements to the params hash, including decoding, to be sorted the same way you have on your page (thus allowing the <code>each_with_index</code> strategy). You need to use the <code>"position"</code> attribute from the query params, which is currently blank. I'm sure there are a million ways to sort and populate that field, google will probably have lots of info on how to do that.</p> <p>So, your final function should look something like:</p> <pre><code>params[:template][:questions_attributes].to_a.each_with_index do |(id, attrs), index| question = Question.find(id) question.position = attrs['position'] question.save # the less validations you skip the better in the long run. end </code></pre>
 

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