I am converting a User object to json via:
user.to_json :methods => :new_cookies
the new_cookies method is:
cookies.all :include => :fortune, :conditions => {:opened => false}
This embed the cookies inside the user json object, but I want fortune to be embedded inside the cookie object as well. I passed inside :include => :fortune but that doesn’t that work.
Is this possible?
Models:
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
end
class Fortune < ActiveRecord::Base
serialize :rstatuses
serialize :genders
has_many :cookies
has_many :users, :through => :cookies
end
I am not sure that the
:includes => :fortuneoption works as you expect (or perhaps at all) — near the end of this section of the current Rails guides it mentions this option for finder methods other than.all.I assume it works similarly to the new Active Relation query interface, e.g.
Cookies.include(:fortunes).where(:opened => false)— in this case, Rails “eager loads” the related records, meaning fortunes are fetched as part of the query for cookies. This is a performance enhancement, but doesn’t otherwise change the behavior of Rails.As I noted in the comments, I think
as_jsonwill do what you want — it defines what is and is not part of the object when serialized usingto_json. You specify methods that should be called in addition to (or to exclude) the methods of the data-backed object itself, for example, yournew_cookiesmethod.In this example, I have added
as_jsontoUser(which gets Cookie) and also toCookiein hopes that each cookie will nest its fortunes in its JSON. See below for an alternative.In a case where I was writing an API and didn’t need to reflect the nested relationships between objects in the JSON, in the controller, I used something like
to produce parallel nodes (objects) in the JSON.