1

我正在尝试传递一个对象(当前用户)以在为集合呈现 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] 为零。

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

谢谢,魏

4

2 回答 2

1

你在一个数组(@items.to_a)上调用 as_json,你确定这是你想要的吗?如果您尝试在模型上调用它,那么您需要执行类似的操作@items.to_a.map{|i| i.to_json(:user => current_user)} (并且您可能不需要to_a)。

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

于 2010-09-14T08:16:08.040 回答
0

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

def as_json(options={})
  {
      :field1   => self.field1,
      :field2   => self.field2,
      :details  => self.details.map{|d| d.to_json(options)}
  }
end
于 2012-02-07T23:10:26.313 回答