简体   繁体   中英

There is a better way to validate in Rails?

The example below is how I'm authenticating my users today:

def create
    if is_internal_request(params[:authenticity_token])
        @user = User.authenticate(params[:email], params[:password])

        if @user
            session[:user_id] = @user.id
            render :json => true
        else
            render :json => 
            { 
                error:
                {
                    code: 1, 
                    message: t('globals.errors.authentication.user-not-found') 
                } 
            }.to_json
        end
    end
end

Pay attention to this fragment:

render :json => 
{ 
    error:
    {
        code: 1, 
        message: t('globals.errors.authentication.user-not-found') 
    } 
}.to_json

Based on it, I want to know if it's organized and solid. I mean, is that something in the edge of the right way?

Forward thinking

Lets suppose that there are some places in my application that check about user's e-mail availability. I want to be DRY and reuse that verification every time I need to use it. If the way that I'm doing the validation (as below) isn't "perfect" at all, how can I create a validation layer that can be useful every time I want?

I mean, instead of create and recreate that fragment of code each time that I want to validate, what's the best way to do something like this?:

email = params[:email]

unless email_is_available(email)
    render :json => { message: 'E-mail isn't available' }
end

With " what's the best way to do something like this? " I'm saying, where I have to place email_is_available function to get it working right?

Every Controller can access ApplicationController methods as they inherit from it.

Anyways, I'd recommend using a gem like Devise for a more complete solution.

GL & HF.

What about something like this?

  if @user.valid?
    render :json => true
  else
    error_hash = {}
    @user.errors.each{|k,v| error_hash[k] = "#{k.capitalize} #{v}"}
    #this will give you a hash like {"email" => "Email is not available"}
    render :json => {:errors => error_hash}
  end

At the client end, you will get this back (eg as an object called data ), see if there is a value for data.errors and then display the various error messages to the user.

Note i haven't plugged in any translation stuff but you can do that :)

I'd suggest you take a look at Ryan Bates' Railscast on authentication from scratch. It walks you through all the issues and is much lighter weight than relying on something as big and heavy as Devise.

http://railscasts.com/episodes/250-authentication-from-scratch

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM