I’m a newbie to RoR. The problem I am trying to solve is how to pass an array of hashes from JQuery to Rails for saving in the database.
Context
In my application, a user is able to drag-and-drop any number of items onto a canvas. This is done using JQuery.
Then the user can save these items, including their X-Y coordinates.
Conceptually I believe that this is saving an array of hashes, where each hash corresponds to an item and consists of an ItemCode, X-coordinate, Y-coordinate.
I am trying to figure out at each step, what method/technique should be used.
Here’s what I figured out so far:
- ? Save an array of objects in JQuery ?
- Serialize this array using jquery.param
- Pass the resulting string as params to Rails using jquery.ajax
- ?? Rails controller somehow parses this string and saves it in the database??
Key Questions
A. What format should this serialized string take to be easily parsed by Rails?
I believe Jquery.param will generate something like this (in param form):
1[item_code]=432&1[x]=250&1[y]=200&2[item_code]=348… I haven’t been able to find anything to tell me if Rails can figure out that the first 3 terms describe 1 item, the next 3 describe the next item, etc.
B. What is the Rails way to handle this? In other words, what particular methods should I look at as my tools for putting this params string into the database as a several new entries into the database?
And of course, if there’s some completely different way to do this, I’d love to hear it. Thanks.
EDIT
Just to clarify, the ItemCode is meant to be different from the id of the item entry into the database. ItemCode is used to look up characteristics about the item in other tables.
One way:
yields a params hash that looks like
Then in the controller:
In your question, you are generating item ID’s in the client. It’s a better idea to let the DB handle that when you are actually creating the objects to eliminate the need to keep track of unique ID’s. In that case, the ID’s passed to the controller are just arbitrary placeholders, but they do have to be unique in each
.param()call to distinguish one object from another.