Note that there are some explanatory texts on larger screens.

plurals
  1. POEager-loading in Rails 3.1 controller action which responds_to json
    text
    copied!<p>Here's what I have so far:</p> <pre><code>class Show &lt; ActiveRecord::Base belongs_to :event # use default_scope so shows are ordered by date by default default_scope order("date ASC") end class Event &lt; ActiveRecord::Base has_many :shows, :dependent =&gt; :destroy has_and_belongs_to_many :users scope :future, lambda { includes(:shows).joins(:shows).where("shows.date &gt; ?", Date.today).group("event_id") } def start_date shows.first.date end def end_date shows.last.date end def ends_in_future? end_date &gt; Date.today end end </code></pre> <p>I would like to create a controller action to use with jqGrid. So far using <code>Event.includes(:shows).all.to_a</code> returns all the shows in the JSON string, but I can't get hold of <code>start_date</code> and <code>end_date</code>, which is kinda understandable. Is it possible to have derived/calculated properties rendered in JSON? </p> <p>I also notice the shows for each event are not in the JSON string. Is there any way I can get all the events, complete with child shows entities, rendered in the JSON string?</p> <p>Many thanks, Dany.</p> <p>EDIT: Partially solved this by using <code>as_json(:include =&gt; :shows)</code> in the controller action. This returns the event and all the associated shows for each event. The only thing remaining is to figure out how I can include <code>start_date</code> and <code>end_date</code> in the json string...</p> <p>EDIT: Here was my original controller action code - it may not be the best code since I'm still feeling my way around Rails:</p> <pre><code>matches = Event.includes(:shows).all respond_to do |format| format.json {render :json =&gt; matches.as_json(:include =&gt; :shows)} end </code></pre> <p>As it turned out I don't have to run the query first - it can just be part of responding to the json request. I should've read the as_json specs a lot closer first! Here's the solution in my controller action:</p> <pre><code>respond_to do |format| format.json {render :json =&gt; Event.all.as_json(:include =&gt; :shows, :methods =&gt; [:start_date, :end_date])} end </code></pre> <p>That renders everything, including the "derived" method. Unfortunately that seems to generate a lot of queries. This provides the json string I want, but is it the best way? Would love to hear any improved methods.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload