适当的$资源POST参数到Rails

时间:2014-05-07 20:45:23

标签: ruby-on-rails angularjs angular-resource

我正在尝试将一些数据发布到我的Rails 4 API。

资源:

App.factory 'House', ['$resource', ($resource) ->
  $resource '/api/v1/houses/:id', { id: '@id' }
]

资源的JSON表示:

newHouse = {
  "owner_id": "30",
  "name": "test",
  "address_attributes": {
    "street": "somewhere",
    "city": "on",
    "region": "earth"
  }
}

House.save(null, $scope.newHouse)上,服务器日志给我这个:

Processing by Api::V1::HouseController#create as JSON
Parameters: {"owner_id"=>"34", "name"=>"test", "address_attributes"=>{"street"=>"somewhere", "city"=>"on", "region"=>"earth"}, "house"=>{"name"=>"test", "owner_id"=>"34"}}

至少可以说这是不可取的。

  1. owner_idname直接出现在根下方,在“房子”下方 - 我希望只在“房子”下方
  2. address_attributes只会直接显示在根目录下 - 我希望它低于house
  3. 基本上我想要这个:

    Processing by Api::V1::HouseController#create as JSON
    Parameters: {"house"=>{"name"=>"test", "owner_id"=>"34", "address_attributes"=>{"street"=>"somewhere", "city"=>"on", "region"=>"earth"}}}
    

    任何帮助?


    修改

    Rails控制器操作:

    def create
      house = House.new house_params
      if house.save
        head 200
      else
        render json: {
          "error" => "validation errors",
          "detail" => house.errors.messages
          }, status: 422
      end
    end
    def house_params
      fields = [:name, :owner_id, address_attributes: [:street, :city, :region, :country, :postal_code ]]
      params.require(:house).permit(fields)
    end
    

    模型House具有:

    has_one :address
    accepts_nested_attributes_for :address
    

    我不想改变服务器处理数据的方式。许多后端希望参数以我想要的格式保存,甚至jQuery也会在其AJAX调用中完成。 AngularJS应该是要改变的,或者至少允许配置的方式。

1 个答案:

答案 0 :(得分:1)

我不确定您是否正确使用$资源。

编辑:我不确定为什么你的类方法表现得像这样,所提出的请求应该是相同的./EDIT

另一种方法可以做到这一点: 假设您的newHouse模型是这样的:

{
  "owner_id": "30",
  "name": "test",
  "address_attributes": {
    "street": "somewhere",
    "city": "on",
    "region": "earth"
  }
} 

在你的HTML中,你会写一些类似的东西:

<span class="btn btn-danger" ng-click="createNewHouse(newHouse)">Create new house</span>

您的Controller会将createNewHouse()方法绑定到$ scope:

$scope.createNewHouse= function(newHouse){
    var newHouseInstance = new House();
    newHouseInstance.house = newHouse;
    newHouseInstance.$save();
}

上面的代码给了我一个带有此负载的POST请求(来自Chrome开发者控制台的直接副本):

Remote Address:127.0.0.1:8080
Request URL:http://localhost:8080/api/v1/houses
Request Method:POST
Request Payload:

{"house":{"owner_id":"30", "name":"test", "address_attributes":{"street":"somewhere", "city":"on", "region":"earth"}}}

这很好地转化为您在服务器上需要的内容。

祝你好运!