gpt4 book ai didi

ruby-on-rails - 正确的 $resource POST 参数到 Rails

转载 作者:行者123 更新时间:2023-12-01 05:12:37 26 4
gpt4 key购买 nike

我正在尝试将一些数据发布到我的 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"}}

至少可以说,这是不可低估的。
  • owner_idname直接出现在根目录下,在“house”下方 - 我希望只在“house”下方
  • address_attributes仅直接出现在根目录下 - 我希望它低于 house

  • 基本上我想要这个:
    Processing by Api::V1::HouseController#create as JSON
    Parameters: {"house"=>{"name"=>"test", "owner_id"=>"34", "address_attributes"=>{"street"=>"somewhere", "city"=>"on", "region"=>"earth"}}}

    有什么帮助吗?

    编辑

    Rails Controller Action :
    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 应该是一个可以改变的,或者至少允许配置的方式。

    最佳答案

    我不确定您是否正确使用了 $resource。

    编辑:我不确定你的类方法为什么会这样,发出的请求应该是相等的。/编辑

    另一种方法的一个例子是:
    让我们说你的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() 方法绑定(bind)到 $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"}}}

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

    祝你好运!

    关于ruby-on-rails - 正确的 $resource POST 参数到 Rails,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23528072/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com