Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The reason your links aren't being stored in order is that you're not presenting them to the db in order. </p> <p>-- The param object is not an array, even though, to an extent it might look like one. Rather, they are a hash where the keys are integers. You can tell this is true because you need to use </p> <pre><code>params[:links].values.collect </code></pre> <p>if it was an array, you'd use</p> <pre><code>params[:links].collect </code></pre> <p>Any time you use .values method, the key order is indeterminate.</p> <p><strong>Solution</strong></p> <p>I agree with @p.g that you should be very careful about using db id's as an order. Eg suppose you want to change the order later? I often have 'list_order' as a field in my models.</p> <p>To reorder the params, and save in order of the key, try the following:</p> <pre><code>links_param = params[:links] ordered_keys = links_param.keys.sort @links = ordered_keys.collect {|key| @user.links.new(links_param[key])} </code></pre> <p>Added: also note that the keys might well come in as strings, not integers. So if you have more than 10 of them, might be an idea to sort them as integers:</p> <pre><code>ordered_keys = links_param.keys.sort{|a,b| a.to_i &lt;=&gt; b.to_i} </code></pre> <hr /> <p><strong>Added in response to comment about saving the "display_order" --</strong></p> <p>First, add new field to model, :display_order. Be sure to add an index on the field since you'll be sorting on it.</p> <p>Then, in your controller, you need to expose the key to the model. Eg something like this:</p> <pre><code> links_param = params[:links] links_params.keys.each{|key|links_params[key][:display_order] = key.to_i} </code></pre> <p>Now when you build your user.link object, the display_order param will be set too.</p>
    singulars
    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. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      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