在使用CURL发布帖子为我的API创建资源(以RoR编码)时,我在将哈希数组作为参数传递时遇到了一些麻烦。
我有以下JSON,我试图将其用作POST主体的指南:
{
status: 200,
show: {
id: 2,
creator_id: 2,
venue_id: 2,
name: "Rock Rumble",
description: "Another fake event",
created_at: "2016-02-25T00:21:36.343Z",
updated_at: "2016-02-25T00:21:36.812Z"
},
artists: [{
id: 5,
name: "Finntroll",
created_at: "2016-02-25T00:21:36.462Z",
updated_at: "2016-02-25T00:21:36.462Z"
}, {
id: 6,
name: "Moonsorrow",
created_at: "2016-02-25T00:21:36.474Z",
updated_at: "2016-02-25T00:21:36.474Z"
}, {
id: 7,
name: "Amon Amarth",
created_at: "2016-02-25T00:21:36.486Z",
updated_at: "2016-02-25T00:21:36.486Z"
}, {
id: 8,
name: "Satyricon",
created_at: "2016-02-25T00:21:36.498Z",
updated_at: "2016-02-25T00:21:36.498Z"
}],
showURL: "/api/shows/2",
venueURL: "/api/venues/2"
}
我的Show.rb文件如下所示:
belongs_to :creator
belongs_to :venue
has_many :setlists
has_many :artists, :through => :setlists
validates :name, presence: true
validates :description, presence: true
和Setlist这样:
class Setlist < ActiveRecord::Base
belongs_to :artist
belongs_to :show
end
最后艺术家是这样的:
class Artist < ActiveRecord::Base
has_many :setlists
has_many :shows, :through=> :setlists
validates :name, presence: true
end
现在我的Api :: ShowsController就像
def create
@show = Show.new(show_params.except[:artists])
#If there are any artists to be saved with this show
if show_params[:artists].present?
#loop through artists, create artist
else
...
end
end
...
#Validation of params
private
def show_params
params.require(:show).permit(:name, :description, artists: [:name])
end
我可以在没有艺术家的情况下发帖,但我想做的事情如下:
curl \
-H "Accept: application/json" \
-H "Content-type: application/json" \
-X POST \
-d '{"name":"test", "description":"testing post to create", "artists":[{"name":"hey"}] }' \
https://[username].c9users.io/api/shows.json
那么,我如何允许一个嵌套的prop。,并在其中包含一个代表我的POST主体中的艺术家的哈希数组?我做错了什么?
实际上,show_params [:artists] .present? ===错误。
答案 0 :(得分:0)
您可以尝试使用show
密钥在请求正文中包装您的json表示吗?由于您正在执行params.require(:show)
,permit
中的密钥应该由require
指定的密钥包装。
像:
{"show":{"name":"test", "description":"testing post to create", "artists":[{"name":"hey"}]}}