1

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 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.

1 Answer 1

3

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!

Sign up to request clarification or add additional context in comments.

2 Comments

I did actually. It works great for not only the case that you have, but also for validations of any object. Taking advantage of AR validations is amazing.
Sounds intriguing. Thanks again!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.