Note that there are some explanatory texts on larger screens.

plurals
  1. POusing "self" in association declaration (:has_many, :has_one)
    primarykey
    data
    text
    <p>I need to reference a model's self in a :has_many declaration. </p> <p>I have a class we will call Foo. Foo :has_many Bar. Foo has a boolean attribute called randomize that determines the order of the the Bars in the :has_many relationship. If randomize is true, then they are ordered by "RAND()" or "RANDOM()" depending on the DB. If not, they are ordered by id. I HAVE to make this declaration on the association because I am using eager loading. I am well-aware that I can define a method in Foo that returns what I want, but I need to have everything loaded at once or else 400-500 queries are run individually = bad.</p> <pre><code>class CreateFoo &lt; ActiveRecord::Migration def self.up create_table :foos do |t| t.string :name t.boolean :randomize, :default =&gt; false end end end </code></pre> <p>&nbsp;</p> <pre><code>class CreateBar &lt; ActiveRecord::Migration def self.up create_table :bars do |t| t.string :name t.references :foo end end end </code></pre> <p>&nbsp;</p> <pre><code>class Bar &lt; ActiveRecord::Base belongs_to :foo end </code></pre> <p>&nbsp;</p> <pre><code>class Foo &lt; ActiveRecord::Base # this is the line that doesn't work has_many :bars, :order =&gt; self.randomize ? 'RAND()' : 'id' end </code></pre> <p>How do I access properties of <em>self</em> in the has_many declaration? </p> <p>Things I've tried and failed:</p> <ol> <li>creating a method of Foo that returns the correct string</li> <li>creating a lambda function</li> <li>crying</li> </ol> <p>Is this possible?</p> <p>The problem seems to be that the "self" in :has_many ISN'T of type Foo:</p> <pre><code>undefined method `randomize' for #&lt;Class:0x1076fbf78&gt; </code></pre> <p>is one of the errors I get. Note that its a general Class, not a Foo Object... Why??</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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