繁体   English   中英

在Rails中以JSON呈现

[英]Render in JSON in Rails

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

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模块中进行引用,因此我也需要对其进行访问。

如果要在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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM