Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rails style nested params with arrays #8

Merged
merged 1 commit into from
Sep 7, 2011
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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