problem using 'as_json' in my model and 'render :json' => in my controller (rails)

Posted by patrick on Stack Overflow See other posts from Stack Overflow or by patrick
Published on 2011-03-20T01:06:31Z Indexed on 2011/03/20 8:09 UTC
Read the original article Hit count: 137

Filed under:
|
|

Hi everyone. I am trying to create a unique json data structure, and I have run into a problem that I can't seem to figure out.

In my controller, I am doing:

favorite_ids = Favorites.all.map(&:photo_id)
data = { :albums => PhotoAlbum.all.to_json,
         :photos => Photo.all.to_json(:favorite => lambda {|photo| favorite_ids.include?(photo.id)}) }

render :json => data

and in my model:

def as_json(options = {})
  { :name => self.name,
    :favorite => options[:favorite].is_a?(Proc) ? options[:favorite].call(self) : options[:favorite] }
end

The problem is, rails encodes the values of 'photos' & 'albums' (in my data hash) as JSON twice, and this breaks everything... The only way I could get this to work is if I call 'as_json' instead of 'to_json':

data = { :albums => PhotoAlbum.all.as_json,
         :photos => Photo.all.as_json(:favorite => lambda {|photo| favorite_ids.include?(photo.id)}) }

However, when I do this, my :favorite => lambda option no longer makes it into the model's as_json method.......... So, I either need a way to tell 'render :json' not to encode the values of the hash so I can use 'to_json' on the values myself, or I need a way to get the parameters passed into 'as_json' to actually show up there.......

I hope someone here can help... Thanks!

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about ruby