views:

67

answers:

2

A Rails controller receives the POST values in a hash, which has no natural order, but for my application I need it, because the user can change the order of the form fields via Javascript. (via Sortable from jQuery)

Is there any other way to retrieve the posted values in their original ordering?

+1  A: 

Unless you parse the raw post data, it will probably be in a hash anyway. And since hashes aren't ordered, you're screwed.

You can have it passed as an array, though, maintaining the ordering, by making use of Rails' params magics. E.g. "foo[]=bar&foo[]=baz&foo=maz" (same goes for POST params) will give you ["bar", "baz", "maz"] for params[:foo]

August Lilleaas
+2  A: 

Using jQuery sortable, you just need to either

  1. serialize the sortable to a hidden input after each change or in the onSubmit part of your form
  2. serialize the sortable on submit via your jQuery $.post

This will provide you with a param like so: {"item"=>["2", "3", "4", "5", "6", "1", "7"]}

Some examples to get you started:

Example onSubmit (in this case, your order is serialized to params[:serialized_form]):

<FORM ACTION=".." NAME="testform"
    onSubmit="$('#serialized_form').value = $('#sortable').sortable('serialize')">
  <INPUT TYPE="hidden" id="serialized_form" value="">
  ...

Example $.post:

$.post("/", $('#sortable').sortable('serialize'), function(ret){
 // whatever you want to do with the outcome here.
});
semanticart