Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

defaults for to_json in Rails with :include

Let us say I have a model Post which belongs to a User. To convert to json, I do something like this

@reply.to_json(:include => {:user => {:only => [:email, :id]}, 
               :only => [:title, :id])

However, I want to set some defaults for this so I don't have to specify :only everytime. I am trying to override as_json to accomplish this. When I add as_json in User model, it is called when I do @user.to_json but when user is included in @reply.to_json, my overriden as_json for User is ignored.

How do I make this work?

Thanks

like image 489
unamashana Avatar asked Feb 15 '11 07:02

unamashana


2 Answers

You can do this by overriding serializable_hash in your model, like so:

class Reply < ActiveRecord::Base
  def serializable_hash(options={})
    options = { 
      :include => {:user => {:only => [:email, :id]}, 
      :only => [:title, :id]
    }.update(options)
    super(options)
  end
end

This will affect all serializable methods, including serializable_hash, to_json, and to_xml.

like image 150
Ryenski Avatar answered Nov 27 '22 02:11

Ryenski


In the Reply model:

def as_json(options = {})
   super options.merge(:methods => [:user], :only => [:id, :title])
end

And in the User model:

def as_json(options = {})
   super options.merge(:only => [:id, :email])
end

When the association is included as a method and not an include, it will run the .to_json on it.

like image 27
Nothus Avatar answered Nov 27 '22 02:11

Nothus