我正在使用事件模型序列化器,并且需要包含 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/