access properties of current model in has_many declaration

Posted by seth.vargo on Stack Overflow See other posts from Stack Overflow or by seth.vargo
Published on 2010-12-30T04:12:04Z Indexed on 2010/12/30 4:53 UTC
Read the original article Hit count: 216

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:

  1. creating a method of Foo that returns the correct string
  2. creating a lambda function
  3. 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??

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about activerecord