views:

51

answers:

1

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

+1  A: 

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).

ormuriauga
Thanks! to_json was the key. To clarify, the to_a was to prevent an error, ActiveSupport::JSON::Encoding::CircularReferenceError (http://osdir.com/ml/RubyonRailsTalk/2010-08/msg00176.html).
yayitswei