giovaZ
giovaZ

Reputation: 1470

Render in JSON in Rails

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.

Upvotes: 1

Views: 239

Answers (1)

Yury Lebedev
Yury Lebedev

Reputation: 4015

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

Upvotes: 3

Related Questions