我有一个使用Devise进行身份验证的本机Rails应用程序(使用token_authenticatable模块)。使用现有帐户,一旦获得令牌,我就可以使用JSON在我的原生iOS应用程序中成功执行API调用。
我想通过iOS应用添加创建新帐户的功能,而无需使用浏览器。 Devise只允许通过HTML创建帐户吗?
我看过这篇文章 Rails/Devise - Creating new users via json request
通过CURL尝试了各种各样的事情,包括:
$ curl -H "Content-Type: application/json" -d '{"email":"who@me.com","password":"mypass"}' -vX POST http://localhost:5000/users.json
...
* Connected to localhost (127.0.0.1) port 5000 (#0)
> POST /users.json HTTP/1.1
> User-Agent: curl/7.24.0 (x86_64-apple-darwin12.0) libcurl/7.24.0 OpenSSL/0.9.8r zlib/1.2.5
> Host: localhost:5000
> Accept: */*
> Content-Type: application/json
> Content-Length: 44
>
* upload completely sent off: 44 out of 44 bytes
< HTTP/1.1 406 Not Acceptable
< Content-Type: application/json; charset=utf-8
< X-Ua-Compatible: IE=Edge
< Cache-Control: no-cache
< X-Request-Id: 338234ca2a6c378426ab67d7a080d44e
< X-Runtime: 0.006427
< Server: WEBrick/1.3.1 (Ruby/1.9.3/2012-12-25)
< Date: Sat, 09 Feb 2013 23:11:19 GMT
< Content-Length: 1
< Connection: Keep-Alive
< Set-Cookie: _MyRailsApp_session=BAh7BkkiD3Nlc3Npb25faWQGOgZFRkkiJTY1ZWIzMTdiYzc5ODdmMzNkOWI5MDM4NTMzYTQ0MWVkBjsAVA%3D%3D--c5871e8577987f36c614483b7a28b08fed55b7b8; path=/; HttpOnly
答案 0 :(得分:7)
启用json for devise
config.navigational_formats = [“ / ”,:json]
并添加新文件
class RegistrationsController < Devise::RegistrationsController
def create
@user = User.create(params[:user])
if @user.save
render :json => {:state => {:code => 0}, :data => @user }
else
render :json => {:state => {:code => 1, :messages => @user.errors.full_messages} }
end
end
end
路线中的:
devise_for :users, :controllers => {:registrations => "registrations"}
<强>更新强>
json也应该看:
{"user" : {"email":"who@me.com","password":"mypass"}}