所以Rails-API应该接受
的JSON帖子{
"post": { "users": [{"name": "James"}]}
}
现在的问题是,我使用的是nested_attributes,在Post模型中我有一行:
`accepts_nested_attributes_for :users`
如何在POST中接受属性名称" users"而不是" users_attributes"?
posts_controller.rb
def create
@post = Post.new(post_params)
users = params.values[0].delete(:users_attributes)
params.values[0][:users] = users
if @post.save
render json: @post, status: :created, location: @post
else
render json: @post.errors, status: :unprocessable_entity
end
end
...
def post_params
users = params.values[0].delete(:users_attributes) params.values[0][:users] = users
params.require(:post).permit(:expiration, :users => [:name, :dates], :users_attributes => [:name, :post_id, :dates => []])
end
end
答案 0 :(得分:0)
你可以试试这个
假设你的参数是
params = { post: {
name: 'war', users_attributes: [
{ title: 'Ruby documentation browser!' },
{ title: 'the modern citizen' },
{ title: '', destroy: '1' }]}}
users = params.values[0].delete(:users_attributes)
params.values[0][:users] = users