加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-17 02:06:27 所属栏目:百科 来源:网络整理
导读:我正在尝试将一些数据发布到我的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":
我正在尝试将一些数据发布到我的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_id和name直接出现在root下面,而在“house”下面 – 我希望只在“house”下面
> address_attributes只会直接出现在root下面 – 我希望它低于房子

基本上我想要这个:

Processing by Api::V1::HouseController#create as JSON
Parameters: {"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
  end
end
def house_params
  fields = [:name,:owner_id,address_attributes: [:street,:city,:region,:country,:postal_code ]]
  params.require(:house).permit(fields)
end

样板房有:

has_one :address
accepts_nested_attributes_for :address

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

解决方法

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

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

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

{
  "owner_id": "30","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"}}}

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

祝好运!

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读