Rails 无法识别 POST 请求中的嵌套 JSON 对象 [英] Rails not recognizing nested JSON objects in POST request
问题描述
基本上,我有两个模型 - 公司和位置.
Basically, I have two models - Company and Location.
class Company < ActiveRecord::Base
has_many :locations, dependent: :destroy
accepts_nested_attributes_for :locations # Not sure if needed.
end
class Location < ActiveRecord::Base
belongs_to :company
end
创建公司时(即对 /companys
的 POST),我希望能够在同一请求中创建其位置.但出于某种原因,我无法让 Rails 识别嵌套在公司内部的位置数组.它似乎撕掉了嵌套的 JSON 数组并将其放入 JSON 请求的根"中.
When creating a Company (i.e. a POST to /companies
), I want to be able to create its Locations in the same request. But for some reason, I cannot get Rails to recognize the array of Locations nested inside the Company. It seems to rip the nested JSON array out and place it into the "root" of the JSON request.
使用 cURL 的 POST 请求示例:
Example POST request using cURL:
curl -X POST -H "Accept: Application/json" -H "Content-Type: application/json" http://example.com/companies -d '{"employee_count":320,"locations":[{"lat":"-47.5", "lon":"120.3"},{"lat":"78.27", "lon":"101.09"}]}'
示例服务器输出:
Started POST "/companies"
Processing by CompaniesController#create as Application/json
Parameters: {"employee_count"=>320, "locations"=>[{"lat"=>"-47.5", "lon"=>"120.3"}, {"lat"=>"78.27", "lon"=>"101.09"}], "company"=>{"employee_count"=>320}}
如您所见,locations
数组不再位于 company
对象内,因此当 CompaniesController#create 尝试创建 Company 实例时,它的 Locations 数组是 <代码>无代码>.另外,employee_count
属性重复了两次,这也有点奇怪.有人知道为什么会发生这种情况以及如何解决吗?
As you can see, the locations
array is no longer inside the company
object, so when CompaniesController#create attempts create the Company instance, it's array of Locations is nil
. Also, the employee_count
attribute is repeated twice, which is kind of strange too. Does anyone know why is this happening and how to fix it?
作为参考,我的 CompaniesController 中的白名单如下所示:
For reference, this is what the whitelist in my CompaniesController looks like:
params.require(:company).permit(
:employee_count,
locations: [:lat, :lon]
)
我的服务器是 Thin (1.6.2),它几乎是一个全新的/默认的 Rails 应用程序,没有特殊配置.
My server is Thin (1.6.2), and it's pretty much an entirely new/default Rails app with no special configurations.
推荐答案
好的,看起来我需要在我的 POST 请求中将 locations
重命名为 locations_updates
(感谢评论中提出此建议的用户).
Okay, looks like I needed to rename locations
to locations_updates
in my POST request (thanks to the users in the comments who suggested this).
我还需要将所有属性封装在外部"company
对象中,而不是位于 JSON 的根"中.示例:
I also needed to encapsulate all attributes in an "outer" company
object, instead of being at the "root" of the JSON. Example:
curl -X POST -H "Accept: Application/json" -H "Content-Type: application/json" http://example.com/companies -d '{"company":{"employee_count":320,"locations":[{"lat":"-47.5", "lon":"120.3"},{"lat":"78.27", "lon":"101.09"}]}}'
这篇关于Rails 无法识别 POST 请求中的嵌套 JSON 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!