質問

Say I have the following form comprising a model and a nested model:

<label>Company Name</label>
<input type="text" ng-model="company.name" />

<label>Owner Name</label>
<input type="text" ng-model="company.owner.name" />

Which I post like this:

Restangular.all('companies').post($scope.company);

What I'm expecting on the server end (in this case Rails) is a nested hash something like this:

company:
    name: Test Company
    owner:
        name: Test Owner

But what I'm getting is this:

name: Test Company
company:
    name: Test Company
owner:
    name: Test Owner

It appears that the models are being flattened, and also the fields from the first model are repeated outside of the scoping.

How can I post the model whilst maintaining its nesting and preferably not repeating the models fields outside of its scope in the hash?

役に立ちましたか?

解決

I'm the creator of Restangular.

Could you console.log the output of $scope.company?

Restangular isn't flattering anything. It's just sending the exact JSon that you've provided as a parameter, that's why you should check what is the output of $scope.company.

After that, we can check it further.

Also, have you checked the network tab for the Payload of the request? Is it OK?

他のヒント

I feel the need to clarify this for anyone else finding this question.

Passing $scope.company passes the JS object that is company that does not include the name of the scope variable itself:

{
    name: 'Test Company',
    owner: {
        name: 'Test Owner'
    }
}

The server will see this as a POST variable named name that is a string with value 'Test Company' and another variable named owner that is an array with an index named name with value of 'Test Owner`

In PHP it would be this:

$_POST['name']; // would = 'Test Company'
$_POST['owner']; // would = array('name'=>'Test Owner')

If you want it to be an array of properties on the server side referred to as company then you need to encapsulate $scope.company in a JS object itself with a property titled "company":

$scope.company = {
     company: {
         name : 'Test Company',
         owner : {
             name : 'Test Owner'
         }
     }
};

Now on the server side you'll find this:

$_POST['company']; // would = array('name'=>'Test Company','owner'=>array('name'=>'Test Owner'))
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top