我正在使用 Rails 4.1 构建一个应用程序,它有一个用户 Controller 和一个单独的 API Controller ,用于在 /v1/users
获取和发布基本用户数据(将在专用子域中提供制作)。
我的 API::V1:UsersController 继承自 ActionController::Base 并具有以下创建方法:
# POST /v1/users
def create
@user = User.create(params[:user])
if @user.save
render :json => @user
else
render :json => { :errors => @user.errors.full_messages }, :status => 422
end
end
在我的主要 UsersController 中,创建方法如下所示:
def create
@user = User.new(user_params)
@user.save
redirect_to @user
end
private
def user_params
params.require(:user).permit(:first_name, :last_name, :email, :birthdate)
end
...然后 routes.rb 像这样将所有内容联系在一起:
namespace :api, :path => "/", defaults: { format: 'json' } do
namespace :v1 do
resources :users
end
end
resources :users
但是,当我尝试通过 curl 或其他脚本向 http://localhost/v1/users
发送内容类型为:application/json 时,新用户对象以 JSON 格式返回,但没有任何内容保存到 Postgres(我使用 UUID 作为用户表的主键)。用户记录已创建,但除了时间戳之外哈希完全为空:
{
"id": "c63b559d-edf3-454d-bcb7-a0b8e5c04c10",
"first_name": null,
"last_name": null,
"email": null,
"birthdate": null,
"created_at": "2014-06-04T23:45:15.046Z",
"updated_at": "2014-06-04T23:45:15.046Z"
}
我在 development.log 中的控制台输出如下所示:
Started POST "/v1/users" for 127.0.0.1 at 2014-06-04 19:32:28 -0400
Processing by API::V1::UsersController#create as JSON
Parameters: {"{ \"email\": \"test@example.com\" }"=>nil}
[1m[36m (0.1ms)[0m [1mBEGIN[0m
[1m[35mSQL (0.3ms)[0m INSERT INTO "users" ("created_at", "updated_at") VALUES ($1, $2) RETURNING "id" [["created_at", "2014-06-04 23:32:28.105402"], ["updated_at", "2014-06-04 23:32:28.105402"]]
[1m[36m (0.9ms)[0m [1mCOMMIT[0m
[1m[35m (0.1ms)[0m BEGIN
[1m[36m (0.1ms)[0m [1mCOMMIT[0m
Completed 200 OK in 3ms (Views: 0.2ms | ActiveRecord: 1.4ms)
我在这里缺少什么吗?看起来参数甚至没有被 create 方法接收到,而且它们肯定不会进入 psql。任何帮助将不胜感激!
最佳答案
json格式错误。试试这个:
{"user":{
"first_name": "string",
"last_name": "string",
"email": "string",
"birthdate": "string",
}}
只要 params.require(:user) 需要对象名称。
Rails JSON request is not parsed correctly into post parameters
关于ruby-on-rails - 为什么我的 Rails API 没有将任何内容保存到数据库中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24049463/