I've got a controller with a single index action:
chat_room_controller.rb
class ChatRoomController < ApplicationController
before_action :authenticate_user
def index
@current_user = User.find(session[:user_id])
end
end
I need to render my variable @current_user in JSON format. So I need to create a show action or I can simply handle this situation adding:
respond_to do |format|
format.json
end
I need the format JSON of this variable for reference in an AngularJS module so I also need access to it.
If you want to have the current_user
method to be available in your rails views, you should create a helper method in your ApplicationController
, and then in all controllers, which inherit from it, the view will have the current_user
helper:
class ApplicationController
protected
def current_user
@current_user ||= User.find(session[:user_id])
end
helper_method :current_user
end
class ChatRoomController < ApplicationController
def index
render json: current_user
end
end
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.