I have models like this:
class User < ActiveRecord::Base
has_many :cookies
has_many :fortunes, :through => :cookies
def new_cookies
cookies.all :include => :fortune, :conditions => {:opened => false}
end
end
class Cookie < ActiveRecord::Base
belongs_to :user
belongs_to :fortune
def self.find_by_shortened_id(shortened_id)
find(shortened_id.alphadecimal)
end
def shortened_id
self.id.alphadecimal
end
end
class Fortune < ActiveRecord::Base
serialize :rstatuses
serialize :genders
has_many :cookies
has_many :users, :through => :cookies
end
I need to convert a User object to json, but I want it to include all cookies with are new (via new_cookies method), and embed in those cookies a) shortened_id and b) the id of it’s fortune.
Is this possible with to_json?
I have the follow so far which gives me the new cookies:
user.to_json :methods => :new_cookies
But I am stuck at trying to figure out how to include in the cookie object the value returned by method shortened_id and the cookies’s fortune’s id.
You may override
as_jsonin your user model.If these types of JSON customizations are needed in several places in your application, you should have a look at the jbuilder gem for rendering your JSON.