I have two models where A has_many B. If I load A including associated B as such:
a = A.find(:first, include: :bs)
a.inspect only shows the attributes of a:
=> "#<A id: 1, name: \"Test\", created_at: \"2012-07-02 21:50:32\", updated_at: \"2012-07-02 21:50:32\">"
How can I do a.inspect such that it displays all associated a.bs?
You can’t do that by default. It might create too many problems and side effects with inspecting objects. However you could extend
inspectyourself with something like this:Note though that that’s not very clever, since it will force the loading of
bsevery time you inspect anAinstance. So maybe you want to be smarter and do something like this:This will only inspect
bsif it’s already preloaded (with:includefor example).Or maybe you want to create a
super_inspectinstead that does everything automatically. You could extendActiveRecord::Basewith something like:This will automatically look up all the associations with
reflect_on_all_associations, and if the association is loaded it will callinspecton that.Now you can modify the above code however you want to create your own customized inspect, or just extend the current inspect if you like. Anything is possible with a little bit of code.
Here is an example of an updated version that is a bit smarter: