【问题标题】:passing values into as_json via options hash?通过选项哈希将值传递给 as_json?
【发布时间】:2010-09-14 07:53:39
【问题描述】:

我正在尝试传递一个对象(当前用户),以便在为集合呈现 json 时使用。

respond_to do |format|
  format.html # index.html.erb
  format.xml  { render :xml => @items }
  format.json { render :json => @items.to_a.as_json(:user => current_user) }
end

但是,这似乎没有任何效果,因为 as_json 方法中的 options[:user] 为 nil。

JSON_ATTRS = ['id', 'created_at', 'title', 'content']
def as_json(options={})
  # options[:user] is nil!
  attributes.slice(*JSON_ATTRS).merge(:viewed => viewed_by?(options[:user]))
end

有人知道为什么这不起作用,或者可以建议一种更优雅的方式让 json 渲染器了解当前用户吗?

谢谢, 魏

【问题讨论】:

    标签: ruby-on-rails json devise


    【解决方案1】:

    您在数组 (@items.to_a) 上调用 as_json,您确定这是您想要的吗? 如果你想在你的模型上调用它,那么你需要做一些类似@items.to_a.map{|i| i.to_json(:user => current_user)}的事情(你可能不需要to_a)。

    你应该打电话给to_json。它将调用 as_json 来获取您的属性,传递您提供的任何选项,但返回格式正确的 json 字符串(as_json 返回一个 ruby​​ 对象)。

    【讨论】:

    【解决方案2】:

    顺便说一句,如果您想将选项传递给“子”关联,我发现这是可行的(至少在 mongo_mapper 支持的项目中):

    def as_json(options={})
      {
          :field1   => self.field1,
          :field2   => self.field2,
          :details  => self.details.map{|d| d.to_json(options)}
      }
    end
    

    【讨论】:

      猜你喜欢
      • 2013-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-22
      • 2016-08-13
      • 2011-08-10
      • 1970-01-01
      • 2012-05-15
      相关资源
      最近更新 更多