Rockwell Rice Rockwell Rice - 1 year ago 108
Ruby Question

How to get user id in ruby on rails app views

In laravel I am use to having


which I can reference for setting up data-id's or something in views. I am working in a ruby on rails app and cannot for the life of me find an answer to how to achieve this in rails. I found a lot of answers talking about current_user but I cannot get any data in the view.

To be clear what I am try to set up exactly is

<a href="/chapters/<%=>" data-user-id="<%= %>"> Enroll </a>

Here the "" would be that users id. With the code above (and any variation of it I can think of) I am getting nothing, no errors but no data either. Do I really have to set this up in every controller method to access it somehow? Does anyone have a solution to this that they can point me towards?

Thanks so much for any help.

Answer Source

If you're going to access any instance variable in a view, you need to define it first (either in a controller or in the view).

Depending on how you have auth set up, you probably have a current_user method somewhere.

It could be defined in ApplicationController (which has functionality shared by all controllers);

class ApplicationController < ActionController::Base
  def current_user
    User.find_by id: session["current_user_id"]
    # or whatever
  helper_method :current_user

The helper_method line makes it accessible in your views, so you can write <%= %>.

You could also write some code so that the @current_user instance variable is available in all your views:

class ApplicationController < ActionController::Base
  before_action :define_current_user
  def define_current_user
    @current_user = current_user # call the 'current_user' method defined elsewhere
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download