1

我有一个可以响应 HTML 和 JSON 客户端请求的 rails 3 控制器。这个控制器有一个“create”方法,它创建一个新的“用户”模型对象,其值发布在 params[:user] 中。当用户参数值从 HTML 表单发布时,这将按预期工作。但是,当从 JSON 客户端(在我的情况下为 iOS)发布到此操作时,params[:user] 为 nil;我确实注意到,如果直接访问 params 哈希确实包含正确的值,即 params[:username] => "someusername"

我需要在 HTTP 请求中添加什么内容,以便可以在控制器中使用 params[:model_name] 语法吗?我正在使用 ASIFormDataRequest.m 发布到我的 Rails 应用程序。

我的客户端 POST 如下所示:

-(void)createUser:(NSString *)first
     lastName:(NSString *)last
     userName:(NSString *)user
        email:(NSString *)email
     password:(NSString *)password{

NSString *stringFormat = [NSString stringWithFormat:@"%@users.json", serviceBaseURL];
NSURL *url = [NSURL URLWithString:stringFormat];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
User *requestedUser = [[User alloc]initWithId:nil firstName:first lastName:last userName:user email:email password:password];
request.tag = CREATE_USER;
request.userInfo = [NSDictionary dictionaryWithObject:requestedUser forKey:@"requestedUser"];
[request setPostValue:first forKey:@"first_name"];
[request setPostValue:last forKey:@"last_name"];
[request setPostValue:user forKey:@"username"];
[request setPostValue:email forKey:@"email"];
[request setPostValue:password forKey:@"password"];
request.Delegate = self;
[request startAsynchronous];

}

控制器的“创建”方法如下所示:

 def create
  @user = User.new(params[:user])      
  if @user.save  #This will fail because params[:user] is nil when posted from iOS!
    flash[:notice] = {:success => "User Created."}
    session[:user_id] = @user.id
        session[:username] = @user.username
         respond_to do |format|
            format.json {render :json => @user}
            format.html{redirect_to(:controller => 'lists', :action => 'index')}
         end

  else
     flash[:notice] = {:error => @user.errors}
      respond_to do |format|
         #format.json {render :json => @user.errors}
         format.json {render :json => params[:username]} #This has a value. So the form parameters are sent.
         format.html{render('new')}
      end
  end
end
4

1 回答 1

4

问题是我需要以 RoR 期望的格式发布我的 JSON。POST 数据的格式如下:

{first_name: "somename", last_name: "somelastname", username: "someusername", etc...}

我的 RoR 控制器期望将属性包装在模型对象中,如下所示:

{user:{first_name: "somename", last_name: "somelastname", username: "someusername", etc...}}

使用 ASIFormDataRequest 这可以通过格式化您的 post 参数来完成,如下所示:

[request setPostValue:first forKey:@"user[first_name]"];
[request setPostValue:last forKey:@"user[last_name]"];
[request setPostValue:user forKey:@"user[username]"];
[request setPostValue:email forKey:@"user[email]"];
[request setPostValue:password forKey:@"user[password]"];

注意'model_name[parameter]' 格式。

于 2012-12-06T16:48:26.367 回答