Skip to content

Commit

Permalink
Rails style nested params with arrays
Browse files Browse the repository at this point in the history
* ie. note[item_ids][]=1&note[item_ids][]=2
  • Loading branch information
ismasan committed Aug 31, 2011
1 parent 7ca3dc4 commit 9accd26
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 4 deletions.
15 changes: 11 additions & 4 deletions src/davis.request.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,15 +38,22 @@ Davis.Request = function (raw) {
Davis.utils.forEach(this.queryString.split("&"), function (keyval) {
var paramName = keyval.split("=")[0],
paramValue = keyval.split("=")[1],
nestedParamRegex = /^(\w+)\[(\w+)\]/,
nestedParamRegex = /^(\w+)\[(\w+)\](\[\])?/,
nested;

if (nested = nestedParamRegex.exec(paramName)) {
var paramParent = nested[1];
var paramName = nested[2];
var isArray = nested[3];
var parentParams = self.params[paramParent] || {};
parentParams[paramName] = paramValue;
self.params[paramParent] = parentParams;

if(isArray != undefined) {
parentParams[paramName] = parentParams[paramName] || [];
parentParams[paramName].push(paramValue);
self.params[paramParent] = parentParams;
}else {
parentParams[paramName] = paramValue;
self.params[paramParent] = parentParams;
}
} else {
self.params[paramName] = paramValue;
};
Expand Down
12 changes: 12 additions & 0 deletions tests/test_request.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,18 @@ test("parsing rails style nested params", function () {
}}, request.params, "should combine the nested params into a separate object under params")
})

test("parsing rails style nested params with arrays", function () {
var request = factory('request', {
fullPath: '/foo?note[ids][]=123&note[ids][]=asdf&note[bars][]=1&note[bars][]=2&note[li]=li'
})

same({note: {
ids: ['123','asdf'],
bars: ['1', '2'],
li: 'li'
}}, request.params, "should combine the nested params into a single array")
})

test("generating a request for the initial page load", function () {
var request = Davis.Request.forPageLoad()

Expand Down

0 comments on commit 9accd26

Please sign in to comment.