代码之家  ›  专栏  ›  技术社区  ›  yayitswei

通过选项哈希将值作为\ujson传入?

  •  1
  • yayitswei  · 技术社区  · 15 年前

    我试图传递一个对象(当前用户),在为集合呈现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方法中的选项[:user]为零。

    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呈现器了解当前用户?

    谢谢, 世界环境学会

    2 回复  |  直到 14 年前
        1
  •  1
  •   einarmagnus    15 年前

    您正在以数组的形式调用( @items.to_a )你确定这就是你想要的吗? 如果你想在你的模特身上打电话,那么你需要做一些类似的事情 @items.to_a.map{|i| i.to_json(:user => current_user)} (你可能不需要 to_a )

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

        2
  •  0
  •   Jon Kern    14 年前

    顺便说一句,如果您想将选项向下传递给“子”关联,我发现这是有效的(至少在MongoMapper支持的项目上是有效的):

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