ruby-on-rails – 适用于Rails的$resource POST参数

ruby-on-rails – 适用于Rails的$resource POST参数,第1张

概述我正在尝试将一些数据发布到我的Rails 4 API. 资源: App.factory 'House', ['$resource', ($resource) -> $resource '/api/v1/houses/:id', { id: '@id' }] 资源的JSON表示: newHouse = { "owner_id": "30", "name": "test", "add 我正在尝试将一些数据发布到我的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 JsONParameters: {"owner_ID"=>"34","name"=>"test","address_attributes"=>{"street"=>"somewhere","city"=>"on","region"=>"earth"},"house"=>{"name"=>"test","owner_ID"=>"34"}}

至少可以说,这是不可取的.

> owner_ID和name直接出现在root下面,而在“house”下面 – 我希望只在“house”下面
> address_attributes只会直接出现在root下面 – 我希望它低于房子

基本上我想要这个:

Processing by API::V1::HouseController#create as JsONParameters: {"house"=>{"name"=>"test","owner_ID"=>"34","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  endenddef house_params  fIElds = [:name,:owner_ID,address_attributes: [:street,:city,:region,:country,:postal_code ]]  params.require(:house).permit(fIElds)end

样板房有:

has_one :addressaccepts_nested_attributes_for :address

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

解决方法 我不确定您是否正确使用您的$资源.

编辑:我不确定为什么你的类方法行为如此,所提出的请求应该是相等的./EDIT

另一种方法的例子是:
让我们说你的newHouse模型是这样的:

{  "owner_ID": "30","region": "earth"  }}

在你的@R_502_6832@中,你会写如下:

<span  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:8080Request URL:http://localhost:8080/API/v1/housesRequest Method:POSTRequest Payload:{"house":{"owner_ID":"30","name":"test","address_attributes":{"street":"somewhere","city":"on","region":"earth"}}}

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

祝好运!

总结

以上是内存溢出为你收集整理的ruby-on-rails – 适用于Rails的$resource POST参数全部内容,希望文章能够帮你解决ruby-on-rails – 适用于Rails的$resource POST参数所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://www.outofmemory.cn/langs/1269840.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-08
下一篇 2022-06-08

发表评论

登录后才能评论

评论列表(0条)

保存