当我在Rails 3应用程序中通过CURL发布到我的资源时,参数不会一直传递给控制器。
所以当我发布{"favorite_user": {"username": "someuser"}}
时,我最终得到以下参数:
{"format"=>:json, "action"=>"create", "controller"=>"v1/favorite_users"}
这是我的POST请求:
POST /api/favorite_users HTTP/1.1
User-Agent: curl/7.30.0
Host: myapp.com
Content-Type: application/myapp.com; version=1
Accept: application/myapp.com; version=1
Content-Length: 48
{"favorite_user": {"username": "someuser"}}
我的routes.rb:
scope 'api', as: 'api' do
api_version(module: 'V1',
header: {name: 'Accept', value: 'application/myapp.com; version=1'},
defaults: {format: :json}) do
resources :favorite_users, only: [:index, :show, :create]
end
end
rake routes
得出这个:
api_favorite_users GET /api/favorite_users(.:format) V1/favorite_users#index {:format=>:json}
POST /api/favorite_users(.:format) V1/favorite_users#create {:format=>:json}
api_favorite_user GET /api/favorite_users/:id(.:format) V1/favorite_users#show {:format=>:json}
我的控制器:
class V1::FavoriteUsersController < V1::BaseController
# ...
def create
render text: params.to_s
end
end
答案 0 :(得分:1)
假设您使用Versionist gem对API进行版本控制,则需要将Content-Type
标题更改为Rails将理解的内容。您的数据是JSON,因此标头应为Content-Type: application/json
。 Versionist没有告诉Rails如何使用自定义Content-Type
解释和解码传入的请求体,它只查看匹配类型的Accept
标头值。