0

I have a simple service which I'm using to POST data to a Rails controller.

My service looks something like this:

app.service('autoRulesService', function($http) { return({ createRule: createRule }); function createRule() { var request = $http({ method: 'POST', url: '/rules.json', data: { one: 'two } }); return request.then(handleSuccess, handleError); } function handleSuccess() { // body omitted... } function handleError() { // body omitted... } }); 

I use that service in my controller in a pretty standard way:

$scope.saveRule = function() { rulesService.createRule().then(function() { // do stuff... }); } 

The problem is that I get a weird unwanted key in my parameters when I inspect the sent data in the Rails log. Where is the "rule" parameter coming from?

Processing by AutoAnalysis::RulesController#create as JSON Parameters: {"one"=>"two", "rule"=>{}} 

It doesn't appear in the request payload (as inspected in Chrome Dev tools)

request payload

and my controller action is pretty standard (there's no before filters either):

class RulesController < ApplicationController def create # NOTE: I'm referencing an :auto_analysis_rule parameter here because # that's my desired param key name. It doesn't exist in the request # as shown here. render json: Rule.create(params[:auto_analysis_rule]) end end 

and I can't find any mention of $http inferring a root JSON key from the URL or anything in the docs.

Where is the "rule" param key coming from?

1 Answer 1

3

Rails automatically wraps parameters that are attributes of the model. If one were an attribute of the Rule model, the payload would look like: {"rule" => {"one" => "two"}}

This functionality removes the need for a top-level key that contains all attributes. In other words, the following payloads would be treated the same if attr1 and attr2 are fields in the MyModel model:

{ "mymodel" : { "attr1" : "val1", "attr2" : "val2" } } { "attr1" : "val1", "attr2" : "val2" } 

This functionality can be disabled per-controller or app-wide in an initializer. Check out this answer for more information: Rails 3 params unwanted wrapping

Sign up to request clarification or add additional context in comments.

1 Comment

Wow. I've somehow being working with Rails for about 4 years without this occurring to me. I guess I've just never tried to mess with the root key of the JSON object I'm sending up so it always just worked transparently. Thanks.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.