access properties of current model in has_many declaration
- by seth.vargo
Hello, I didn't exactly know how to pose this question other than through example...
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:
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?
UPDATE
The problem seems to be that the class 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??