ruby on rails - Preload Model Associations On Find -


I'm trying to call my model right now, and left its results in json / xml format. My only problem is that my database associations are not being loaded or inquiries are being made.

In general, I can just run it
)

Then get the number of hits by calling, @campaign [ 0]. has_many: hits via.

But if you debug the output, then it only calls the column to the table.

For example:

 & lt; Campaign & gt; & Lt; Category & gt; Website & lt; / Category & gt; & Lt; Made-at type = & quot; Timestamp & quot; & Gt; 2009-01-24 14:49:02 -0800 & lt; / Made-a & gt; & Lt; Finally type = & quot; Date & quot; & Gt; 2009-01-24 & lt; / End-end & gt; & Lt; Id type = & quot; Integer & quot; & Gt; 14 & lt; / Id & gt; & Lt; View type = & quot; Integer & quot; & Gt; 1 & lt; / View & gt; & Lt; Name & gt; Let & lt; / Name & gt; & Lt; Slag & gt; C5334415da5c89384e42ce6d72609dda & lt; / Slag & gt; & Lt; Start-In Type = & quot; Date & quot; & Gt; 2009-01-24 & lt; / Start-at & gt; & Lt; User-ID type = & quot; Integer & quot; & Gt; 5 & ​​lt; / User-id & gt; & Lt; / Campaigns & gt; 

Then instead of adding another column to it, but the number of hits.

 & lt; Campaign & gt; & Lt; Category & gt; Website & lt; / Category & gt; & Lt; Made-at type = & quot; Timestamp & quot; & Gt; 2009-01-24 14:49:02 -0800 & lt; / Made-a & gt; & Lt; Finally type = & quot; Date & quot; & Gt; 2009-01-24 & lt; / End-end & gt; & Lt; Id type = & quot; Integer & quot; & Gt; 14 & lt; / Id & gt; & Lt; View type = & quot; Integer & quot; & Gt; 1 & lt; / View & gt; & Lt; Name & gt; Let & lt; / Name & gt; & Lt; Slag & gt; C5334415da5c89384e42ce6d72609dda & lt; / Slag & gt; & Lt; Start-In Type = & quot; Date & quot; & Gt; 2009-01-24 & lt; / Start-at & gt; & Lt; User-ID type = & quot; Integer & quot; & Gt; 5 & ​​lt; / User-id & gt; & Lt; Hit type = & quot; Integer & quot; & Gt; 123412 & lt; / Hit & gt; & Lt; / Campaigns & gt; 

ActiveRecord Search () includes in the family: option that lets you load your partners eagerly allows for. / P>

All you have to do is:

@campaign = Campaign.find (: all ,: include =>: hits)

The above will be eager to load your database so that each index can reach [0], do not release their own selection call, etc. When you call

@ Campaign [0] .to_json

Then no entities will be included in it, such as "hits" After doing this, you also need to do this: include it on to_json call, e.g.

@ Campaign [0] .to_json (: included =>: hits)


Comments