动态创建一个继承自ActiveRecord的类?

时间:2013-10-11 13:16:04

标签: ruby activerecord

我希望能够动态创建类,用于从我的Rails应用程序之外编写,继承自ActiveRecord。

我坚持这样的事情:

require 'active_record'

def create_arec(table_name)
  Class.new ActiveRecord::Base do
    self.table_name = table_name
    yield
  end
end

Band = create_arec 'bands' do
  scope :only_rock, -> {where genre: 'rock'}
end

rock_bands = Band.only_rock #undefined method `only_rock'

如何让它发挥作用,或者有人能告诉我更好的方法吗?

1 个答案:

答案 0 :(得分:4)

Nailed it:

def create_arec(table_name, &block)
  klass = Class.new(ActiveRecord::Base){self.table_name = table_name}
  klass.class_eval &block
  klass
end

谢谢@phoet