Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><strong>My Solution</strong></p> <p>One possible solution I found is to subclass the model and overwrite the <code>default_scope</code> which can also take a block. I have tested it and it works as expected!</p> <p>But it is important to note that this only works in <code>Rails 3.1</code>, as <code>3.0</code> does <strong>not</strong> accept blocks for the <code>default_scope</code> method (they are just ignored).</p> <p>Here is an example of the models involved:</p> <pre><code>class Other &lt; ActiveRecord::Base has_many :users end class User &lt; ActiveRecord::Base has_one :profile has_one :profile_with_relationship end class Profile &lt; ActiveRecord::Base end class ProfileWithRelationship &lt; Profile set_table_name "profiles" default_scope do select("'#{Time.now}' as virtual_attribute") end end </code></pre> <p>It now works even with nested includes:</p> <pre><code>Other.includes(:users =&gt; :profile_with_relationship).find(1) </code></pre> <p>Will produce:</p> <pre><code>Other Load (0.1ms) SELECT "others".* FROM "others" WHERE "others"."id" = ? LIMIT 1 [["id", 1]] User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."other_id" IN (1) ProfileWithRelationship Load (0.2ms) SELECT '2011-11-23 11:34:15 +0100' as virtual_attribute, "profiles".* FROM "profiles" WHERE "profiles"."user_id" IN (1, 2, 3, 4, 5) </code></pre> <p>In my special case this is fine, as I don't need the values of the stored proc not all the time and can query it now only for the cases I need it.</p> <p>Hope this helps anyone else. :)</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