使用ActiveRecord方法的结构对象? (Ruby on Rails)

时间:2011-03-21 19:24:30

标签: ruby-on-rails ruby memory activerecord object

我有一组有限的对象(20 - 30),我需要能够与ActiveRecord对象结合使用。将它们放入数据库中似乎很糟糕,因为我已经有两个其他连接模型连接到模型。

所以,假设我有一个班级

class Thing < ActiveRecord::Base
  has_many :other_things, :class_name => 'OtherThing'
end

使用现有表格。我怎样才能将它与不继承ActiveRecord的类结合起来(这是我的最佳猜测)

class OtherThing < ActiveRecord::Base
  OtherThing = Struct.new(:id, :name, :age, :monkey_fighting_ability)
  belongs_to :thing, :class_name => 'Thing'

  validate :something

  def self.search_for(something)
    MY_GLOBAL_HASH[something].map do |hash|
      instance = OtherThing.new
      hash.each_pair do |k,v|
        instance.send(:"#{k}=", v)
      end
      instance
    end
  end

  #if AR wants to call save
  def save
    return true
  end
  alias save save!

  protected
    def something
      self.errors.add(:monkey_fighting_ability, 'must be unlimited') if self.class.search_for(something).empty?
    end
end

重点是我想要使用ActiveRecord方法等,而不必使用db。非常感谢帮助。

1 个答案:

答案 0 :(得分:3)

我建议阅读Yehuda Katz撰写的"Make any Ruby Object Feel Like An Active Record"帖子。它讨论了如何在没有数据库支持的情况下将任何对象转换为类似模型的类。

祝你好运!