ruby-on-rails - 带参数的事件模型序列化器?

标签 ruby-on-rails serialization active-model-serializers

我正在使用事件模型序列化器,并且需要包含 Controller 范围内的参数。例如,我正在序列化帖子,但 current_user (PostController 中的变量)和序列化器中的帖子之间存在一个条件。

class PostSerializer < ActiveModel::Serializer
attributes :id, :active, :favorite

def favorite
  if current_user.favorites.find(object.id) != nil
    return true
  end
end

但是,current_user 未定义。无论如何,我可以将 current_user 作为参数发送到序列化器中吗?

非常感谢!

最佳答案

您使用的是哪个版本的事件模型序列化器?无论如何,我使用的是 0.8.3,它有一个选项参数,因此您可以像

那样调用序列化器
PostSerializer.new(post, :current_user => current_user)

并访问 current_user 选项,例如

def favorite
  if options[:current_user].favorites.find(object.id) != nil
    return true
  end
end

但是我怀疑实际序列化恰好与最喜欢的帖子有关系的用户会更干净

关于ruby-on-rails - 带参数的事件模型序列化器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33303575/

相关文章:

ruby-on-rails - jbuilder 与 rails-api/active_model_serializers 在 Rails 4 中处理 JSON

c++ - 是否可以从 clang 的解析树中提取预处理器信息?

php - 如何在php mysql中保存多个序列化数据

ruby-on-rails - 在事件模型序列化程序中禁用 root

ruby-on-rails - 从哈希构造时,ruby-on-rails 的操作顺序是什么?

java - Java 中的序列化问题

ruby-on-rails - 与主动模型序列化程序的急切加载关联

ruby-on-rails - 如何将 IPN 处理程序与 Pay 操作一起使用并接收消息?

ruby-on-rails - rails4 - Psych::BadAlias:未知别名:test

ruby-on-rails - 参数错误 : odd number of arguments for Hash when trying to connect to redis