从JSON创建Devise中的用户

时间:2012-01-12 20:38:06

标签: iphone ruby-on-rails json devise restkit

我正在努力将运行Devise的Rails 3.1应用程序与我的iOS应用程序集成以进行用户身份验证。我希望用户能够从应用程序注册,然后我可以存储这些凭据以便稍后登录。

使用RestKit,我这样做:

-(IBAction)registerUser:(id)sender {
    NSDictionary *params = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:
                                                                self.email.text,
                                                                self.password.text,
                                                                self.confirmPassword.text,
                                                                nil]
                                                       forKeys:[NSArray arrayWithObjects:
                                                                @"email",
                                                                @"password",
                                                                @"password_confirmation",
                                                                nil]];

    [[RKClient sharedClient] post:@"/users.json" params:params delegate:self];
}

/users.json网址转到:user_registration POST /users(.:format) {:action=>"create", :controller=>"devise/registrations"}(根据佣金路线)。看来post调用接受不同的格式,所以我认为它会接受JSON。我的帖子请求被序列化为JSON,并被发送出去。服务器获取它,这是日志:

Started POST "/users.json" for 129.21.84.10 at 2012-01-12 15:33:57 -0500
  Processing by Devise::RegistrationsController#create as JSON
  Parameters: {"password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]", "email"=>"test1@test.com"}
WARNING: Can't verify CSRF token authenticity
  User Load (0.9ms)  SELECT "users".* FROM "users" WHERE "users"."id" = 1 LIMIT 1
   (0.3ms)  BEGIN
   (0.2ms)  COMMIT
   (0.2ms)  BEGIN
   (0.4ms)  ROLLBACK
Completed 422 Unprocessable Entity in 93ms (Views: 3.8ms | ActiveRecord: 10.2ms)

我收到422错误,但我的用户未创建。我的iOS应用获得的响应是​​:Response: {"email":["can't be blank"],"password":["can't be blank"]}。但密码和电子邮件不是空白,服务器成功获得了它们。所以,有些东西不能正常工作,我不知道该去哪里。如何使用JSON创建用户?

感谢您的帮助!

2 个答案:

答案 0 :(得分:6)

我自己也在做同样的事情 - 从iPhone应用程序在Devise中创建用户。我通过POST json看起来像是这样做了:

{"user":{"email":"test@example.com", "password":"Test123", "password_confirmation":"Test123"}}

和网址:

http://localhost:3000/users.json

我的帖子的请求标题Content-Type是'application / json'。

所有标准设计配置。

答案 1 :(得分:5)

您的rails应用程序期望以这种形式使用JSON:

{"user":{"email":"test@example.com", "password":"Test123", "password_confirmation":"Test123"}}

但默认情况下,RestKit发送此信息:

{"email":"test@example.com", "password":"Test123", "password_confirmation":"Test123"}

要添加“user”,您只需要像这样设置rootKeyPath:

RKObjectMapping *userSerializationMapping = [userMapping inverseMapping];
userSerializationMapping.rootKeyPath = @"user";
[[RKObjectManager sharedManager].mappingProvider setSerializationMapping:userSerializationMapping forClass:[User class]];