2013-02-09 147 views
1

我有一个使用Devise进行身份验证(使用token_authenticatable模块)本机Rails应用程序创建设计的用户帐户。使用现有帐户,我可以在获取令牌后,使用JSON在我的本机iOS应用程序中成功执行API调用。通过原生iOS应用

我想通过iOS应用程序添加功能创建一个新帐户,无需使用浏览器。设计是否只允许通过HTML创建帐户?

我看了这个帖子 Rails/Devise - Creating new users via json request

,并通过卷曲尝试过各种东西,包括:

$ curl -H "Content-Type: application/json" -d '{"email":"[email protected]","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 

回答

7

使JSON用于色器件

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"} 

UPDATE

而且JSON应该是:

{"user" : {"email":"[email protected]","password":"mypass"}} 
+1

感谢完整的答案!它运作良好。 – 2013-02-10 05:49:41

+1

为了得到这个HTML和JSON工作,我结束了此解决方案:http://stackoverflow.com/questions/14447835/using-devise-to-sign-up-sign-in-and-sign-out- with-an-ios-app/14800237#14800237 – 2013-02-10 17:07:52

+0

谢谢!我需要添加一个私人方法user_params到控制器白名单:电子邮件和:密码。我也必须按照[建议](http://stackoverflow.com/a/10049965/313633)禁用CSRF保护。 – 2014-03-06 18:40:02