简体   繁体   中英

How to define a current_model for a model in rails?

I think my question title is bit confusing. But what I am meaning to ask is I am creating my own authentication system using mobile. Just like devise comes with current_user to create a session, I want to know how can I achieve same on a different model.

I have a model called Commuter . It also has a id with it. A record of commuter looks like this.

Commuter.last

<Commuter id: 867, phone_number: "9483942090">

I am trying to create a session after verfying the mobile number with my controller method as follows:

def verify
    @commuter = Commuter.where(phone_number: params[:phone_number]).first
    if (@commuter && @commuter.authenticate_otp(params[:otp],drift:300))
      @commuter.auth_active = true
      if @commuter.save
        #Removed from session after verified it
        session[:phone_number] = nil
        session[:is_verified] = nil
        #signed in commuter after verified it
        sign_in(:commuter, @commuter)
        flash[:notice] = "Your mobile no is verified."
      end
    else
      flash[:alert] = "You have entered wrong otp.Please check again."
    end
    puts "#{current_commuter.phone_number}"
    redirect_to root_path
  end

I just a puts there to debug. So right now I am getting current_commuter as undefined local variable for obvious reasons I guess. So I wanted to know how can achieve this session based current commuter ?

You can save the Commuter id in the session as session[:cid] = 1 and create a method on your base controller like this

def current_commuter
  @commuter ||= Commuter.find session[:cid]
end


helper_method :current_commuter

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