我正在为rails中的用户模型开发API。我遵循他的API Railscasts中规定的Ryan Bates惯例,用于版本控制和保护API。以下是相关文件:
module Api
module V1
class UsersController < ApplicationController
def new
@user = User.new
end
def create
@user = User.new(params[:user])
respond_to do |format|
if @user.save
format.json { render json: @user, status: :created, location: @user }
else
format.json { render json: @user.errors, status: :unprocessable_entity }
end
end
end
end
end
end
namespace :api, defaults: {format: 'json'} do
namespace :v1 do
...
resources :users
end
end
现在我试图通过浏览器或通过curl测试通过API创建新用户,但我不知道该怎么做。我正在吐痰,并认为它应该像... ...
api/v1/users/new?email="misats@wintas.com"?password="mypass"?password_confirmation="mypass"
...使用该网址我收到路由错误没有路由匹配[GET]&#34; / new&#34;,所以我猜测是否需要发布路由?任何正确方向的帮助或指示都会受到赞赏。
我添加了这条路线......
match 'create_user' => 'users#create'
..现在我可以做......
api/v1/create_user?email="misats@wintas.com"?password="mypass"?password_confirmation="mypass"
......我收到了这个错误...
MultiJson::LoadError in Api::V1::UsersController#create
JSON::ParserError
Rails.root: /home/johnmlocklear/railsApps/dca_dummy
Application Trace | Framework Trace | Full Trace
app/controllers/api/v1/users_controller.rb:8:in `create'
Request
Parameters:
{"email"=>"\"misats@wintas.com\"?password=\"mypass\"?password_confirmation=\"mypass\"",
"format"=>"json"}
好的,我意识到我正走错了路。我试图在浏览器中测试它。我意识到我应该用卷曲之类的东西做这件事。我正在尝试这个...
curl -H "Content-Type: application/json" -d '{"user":{"email":"mistas@wintas.com","password":"mypass","password_confirmation":"mypass"}}' http://localhost:3000/api/v1/users
...在控制台中我看到了......
NoMethodError (undefined method `call' for #<User:0x9ed8614>):
app/controllers/api/v1/users_controller.rb:8:in `create'
任何帮助表示感谢。
答案 0 :(得分:0)
您应该指定一个帖子创建请求:
api/v1/users/create?#{whatever parameters you want to pass}
'api/v1/users/new'
仅作为get请求工作,并为您提供用户对象的空模板。
您可以运行rake routes
命令查看路由列表及其类型
答案 1 :(得分:0)
我试图通过浏览器这样做是错误的。通过粘贴URL进行的大多数调用本身就是http&#39; get&#39;调用。我最终使用了这个curl命令......
curl -H "Content-Type: application/json" -d '{"user":{"email":"mistas@wintas.com","password":"mypass","password_confirmation":"mypass"}}' http://localhost:3000/api/v1/users
...通过http&#39; post&#39;。
创建用户