You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ruby技术问题:如何向Oj Serializer传递参数?

如何在Oj Serializer中从控制器传递变量

Oj Serializer提供了两种常用方式来从控制器向Serializer传递额外变量(比如current_user):

方式一:使用context参数

这是Oj Serializer推荐的标准方式,适合传递通用上下文数据。

控制器代码修改:

class AlbumsController < ApplicationController
  def index
    # 通过context参数传入current_user
    render json: { albums: AlbumSerializer.many(albums, context: { current_user: current_user }) }
  end
end

Serializer中访问变量:

在Serializer类里,通过context方法即可获取传入的变量:

class AlbumSerializer < Oj::Serializer
  attributes :id, :name, :user_has_access

  def user_has_access
    # 使用context中的current_user判断权限
    context[:current_user]&.can_access?(object)
  end
end

方式二:直接传递关键字参数

如果只需要传递特定变量,可以直接在调用Serializer时传入关键字参数,然后在Serializer中通过options方法或自定义实例变量访问。

控制器代码修改:

class AlbumsController < ApplicationController
  def index
    # 直接传入current_user作为关键字参数
    render json: { albums: AlbumSerializer.many(albums, current_user: current_user) }
  end
end

Serializer中访问变量(两种写法):

写法1:使用options方法直接获取

class AlbumSerializer < Oj::Serializer
  attributes :id, :name, :user_has_access

  def user_has_access
    options[:current_user]&.can_access?(object)
  end
end

写法2:通过初始化方法定义实例变量

class AlbumSerializer < Oj::Serializer
  attributes :id, :name, :user_has_access
  attr_reader :current_user

  def initialize(object, **options)
    @current_user = options[:current_user]
    super # 必须调用super完成父类初始化
  end

  def user_has_access
    current_user&.can_access?(object)
  end
end

内容的提问来源于stack exchange,提问作者Steven

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 03:32:02