Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 在Rails中用JSON呈现_Ruby On Rails_Ruby_Json - Fatal编程技术网

Ruby on rails 在Rails中用JSON呈现

Ruby on rails 在Rails中用JSON呈现,ruby-on-rails,ruby,json,Ruby On Rails,Ruby,Json,我有一个控制器,它有一个索引动作: 聊天室控制器.rb class ChatRoomController < ApplicationController before_action :authenticate_user def index @current_user = User.find(session[:user_id]) end end 我需要这个变量的JSON格式,以便在AngularJS模块中引用,因此我还需要访问它。如果您想在rails视图中使用当前用

我有一个控制器,它有一个索引动作:

聊天室控制器.rb

class ChatRoomController < ApplicationController

  before_action :authenticate_user

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

我需要这个变量的JSON格式,以便在AngularJS模块中引用,因此我还需要访问它。

如果您想在rails视图中使用
当前用户
方法,您应该在
应用程序控制器
中创建一个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
类应用程序控制器
受保护的
def当前用户
@当前_用户| |=user.find(会话[:user_id])
结束
助手\u方法:当前\u用户
结束
类聊天室控制器<应用程序控制器
def索引
呈现json:当前用户
结束
结束

您好,谢谢您的回答!我忘了指定(刚刚添加)我需要这个变量的JSON数据,以便在Angular JS模块中使用它。如果只是渲染这个,则当前用户不需要@。好的,但是我如何从Angular访问@current_用户数据?当您获得索引url时,您将当前_用户对象格式化为JSON。谢谢。如果我需要将这个变量用于rails(用于html文件中的标记)和JSON(用于此变量),还有一件事吗?
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