I need to reference a model’s self in a :has_many declaration.
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.
class CreateFoo < ActiveRecord::Migration
def self.up
create_table :foos do |t|
t.string :name
t.boolean :randomize, :default => false
end
end
end
class CreateBar < ActiveRecord::Migration
def self.up
create_table :bars do |t|
t.string :name
t.references :foo
end
end
end
class Bar < ActiveRecord::Base
belongs_to :foo
end
class Foo < ActiveRecord::Base
# this is the line that doesn't work
has_many :bars, :order => self.randomize ? 'RAND()' : 'id'
end
How do I access properties of self in the has_many declaration?
Things I’ve tried and failed:
- creating a method of Foo that returns the correct string
- creating a lambda function
- crying
Is this possible?
The problem seems to be that the “self” in :has_many ISN’T of type Foo:
undefined method `randomize' for #<Class:0x1076fbf78>
is one of the errors I get. Note that its a general Class, not a Foo Object… Why??
Turns out Ryan Bates has touched on a simliar topic here in a Railscast. You need to define the scope AFTER the method…