Note that there are some explanatory texts on larger screens.

plurals
  1. POLoad several ActiveRecord models in one query
    text
    copied!<p>My application is on Rails 2.</p> <p>I have 2 models, joined by a <code>has_and_belongs_to_many</code> relation : <code>Message</code> and <code>Conversation</code>. So I have 3 tables, <code>messages</code>, <code>conversations</code> and <code>conversations_messages</code>.</p> <p>Is it possible to load in one unique query both objects <code>Message</code> and <code>Conversation</code>, without using the <code>:include</code> option ? The <code>:include</code> option is impossible because my query depends of some external params.</p> <p>Example :</p> <p>I can do a query from Message to have a couple of (<code>Message</code>,<code>Conversation</code>) per line</p> <pre><code>messages = Message.find(:all, :select =&gt; "messages.*, conversations.*", :conditions =&gt; some_conditions_depending_of_external_variables :group =&gt; "messages.id" ) </code></pre> <p>The resulting table looks like :</p> <pre><code>`messages`.id | `messages`.field | `conversations`.id | `conversations`.field --------------+------------------+--------------------+------------------ 1 | ... | 10 | ... --------------+------------------+--------------------+------------------ 2 | ... | 15 | ... --------------+------------------+--------------------+------------------ 3 | ... | 10 | ... --------------+------------------+--------------------+------------------ 4 | ... | 20 | ... </code></pre> <p>After this query, my variable <code>messages</code> contains a set of AR Messages elements, but the conversations fields are not loaded as an AR Conversation.</p> <p>I want to be able to call a message.linked_conversation to have the conversation of the same line, as an AR object.</p> <p>Is there any method to do this without re-loading the objects ?</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