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 theto_a).And it is
to_jsonyou 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_jsonreturns a ruby object).