Rails作为后端API

时间:2013-12-31 02:39:05

标签: ruby-on-rails

我对rails完全不熟悉(实际上这是我的第1天的rails)。我正在尝试为我的iOS应用程序开发后端。这是我的创建用户方法。

def create 

    user = User.find_by_email(params[:user][:email])

    if user 
      render :json => {:success => 'false', :message => 'Email already exists'}
    else 
      user = User.new(user_params)
      if user.save
      render :json => {:success => 'true', :message => 'Account has been created'}
      else 
      render :json => {:success => 'false', :message => 'Error creating account'}
      end 
    end 

  end 

我怎样才能让它变得更好?

2 个答案:

答案 0 :(得分:1)

您可以使用HTTP状态代码,但如果您的API不会被除iOS应用之外的任何内容使用,那么它可能会过度。

答案 1 :(得分:0)

我这样做的方法是将验证放在模型的一边,让ActiveModel填充错误。状态代码也非常有用。

class User < ApplicationModel
  validate_uniqueness_of :email
  # Other useful code
end

class UsersController < ApplicationController
  def create
    @user = User.new(params.require(:user).permit(:email)) # `require` and `permit` is highly recommended to treat params

    if @user.save # `User#save` will use the validation set in the model. It will return a boolean and if there are errors, the `errors` attributes will be populated
      render json: @user, status: :ok # It's good practice to return the created object
    else
      render json: @user.errors, status: :unprocessable_entity # you'll have your validation errors as an array
    end
  end
end