title: Loop Ajax Data in Rails Controller
body: <p>I have a sort function that triggers when I re-order list items.</p>
  <pre class="lang-js prettyprint-override"><code>var articleIds = [];
  document.querySelectorAll('.article').forEach(item =&gt;
    articleIds.push(item.dataset.id)
  );
  
  Rails.ajax({
    url: '/u',
    type: 'patch',
    data: articleIds
  });
  </code></pre>
  <p>The articles start as <code>[ &quot;52&quot;, &quot;29&quot;, &quot;30&quot;, &quot;51&quot; ]</code>. After the sort <code>console.log(articleIds)</code> shows them as <code>[ &quot;51&quot;, &quot;52&quot;, &quot;29&quot;, &quot;30&quot; ]</code>. So far, so good.</p>
  <p>Trying to see what data I'm getting in the Rails server logs, I've tried:</p>
  <pre class="lang-rb prettyprint-override"><code>params[:id].map.with_index do |id, position|
    puts &quot;position: #{position}, id: #{id}&quot;
  end
  </code></pre>
  <p>It returns: <code>NoMethodError (undefined method 'map' for nil:NilClass):</code></p>
  <p>Thinking this was returning some type of JSON object, I tried:</p>
  <pre class="lang-rb prettyprint-override"><code>articles = JSON.parse(params[:id])
  articles.map.with_index do |id, position|
    puts &quot;position: #{position}, id: #{id}&quot;
  end
  </code></pre>
  <p>This returns the same: <code>NoMethodError (undefined method 'map' for nil:NilClass):</code></p>
  <p>If I use <code>each_with_index</code> instead of <code>map</code> I get <code>TypeError (no implicit conversion of nil into String):</code></p>
  <p>How do I loop this Ajax data in a Rails controller?</p>
  <p><strong>Answer:</strong></p>
  <p>I used the <code>Rails.ajax</code> call in the accepted answer. This created a string so I had to add <code>.split(',')</code> to the block in the controler:</p>
  <pre class="lang-rb prettyprint-override"><code>params[:id].split(',').map.with_index do |id, position|
    puts &quot;position: #{position}, id: #{id}&quot;
  position)
  end
  </code></pre>