在Rails中呈现JSON

时间:2015-08-13 14:16:54

标签: ruby-on-rails ruby json

我有一个带有单个索引操作的控制器:

chat_room_controller.rb

class ChatRoomController < ApplicationController

  before_action :authenticate_user

  def index
    @current_user = User.find(session[:user_id])
  end
end

我需要以JSON格式渲染变量@current_user。所以我需要创建一个show动作,或者我可以简单地处理这种情况添加:

respond_to do |format|
  format.json
end

我需要此变量的格式JSON以供AngularJS模块中的参考,因此我还需要访问它。

1 个答案:

答案 0 :(得分:3)

如果您希望在rails视图中使用current_user方法,则应在ApplicationController中创建一个帮助方法,然后在从其继承的所有控制器中创建一个帮助方法将拥有current_user帮助:

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