开发者

passing values into as_json via options hash?

I'm trying to pass an object (the current user) to be used when rendering the json for a collection.

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

However, this seems to have no effect as options[:user] is nil in the as_json method.

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

Anyone know why this doesn't work, or can suggest a more elegant way to have the json renderer be aware of the current user?

Thanks, Wei


you are calling as_json on an Array (@items.to_a), are you sure that is what you want? If you are trying to call it on your models then you need to do something like @items.to_a.map{|i| i.to_json(:user => current_user)} (and you probably don't need the to_a).

And it is to_json you should be calling. It will invoke as_json to get your properties, passing along whatever options you provide it with, but return a properly formated json-string (as_json returns a ruby object).


BTW, if you want to pass the options on down to "child" associations, I found that this worked (at least on a mongo_mapper backed project):

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜