开发者

Struct Objects with ActiveRecord methods? (Ruby on Rails)

I have a limited set of objects (20 - 30) which I need to be able to combine with ActiveRecord Objects. Putting them into the DB just seems awful because I already have two other join models hooked up to the model.

So let's say i have a class

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

with an existing table. How would I be able to combine this with开发者_JAVA技巧 a class not inheriting from ActiveRecord (here's my best guess)

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

Point being that I want to use ActiveRecord methods and so on without ever hitting the db. Help is greatly appreciated.


I'd suggest reading the post on "Make any Ruby Object Feel Like An Active Record" by Yehuda Katz. It goes over how to convert any object into a model-like class, without the database backing.

Good Luck!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜