sands
sands

Reputation: 342

How Do I Add Methods To ActiveRecord::Base?

I'm trying to create a customized ActiveRecord::Base that includes additional metadata about the connection. I see two ways to go about this:

1.) Inherit from ActiveRecord::Base and add methods & fields in this subclass.

2.) Encapsulate an ActiveRecord::Base object inside my own class

1 has all kinds of problems with the inability to override initialize, weird problems where it doesn't seem to have custom methods I've added, etc.

undefined method `set_profile' for #<Class:0xf041f0>

2 I have not been able to figure out, due to problems with using ActiveRecord::Base.new

I am trying to make an all-purpose ActiveRecord class that I can dynamically establish_connection & set_table_name on, (i.e. not have one underlying table that this ActiveRecord::Base represents) but I can't seem to find a way to accomplish it. Any ideas?

This works:

  class MyTable < ActiveRecord::Base
    establish_connection $config['custom-db-config'];
    set_table_name 'MY_TABLE'
  end

but I need a class I can call these things on repeatedly.

Upvotes: 4

Views: 3062

Answers (2)

Aditya Kapoor
Aditya Kapoor

Reputation: 1570

You can also extend the ActiveRecord::Base class in order to add the those methods dynamically which are directly callable by the class inheriting the ActiveRecord::Base...Many acts_as plugins are defined and made according to this practice...

Upvotes: 0

Benjamin Tan Wei Hao
Benjamin Tan Wei Hao

Reputation: 9691

Not entirely sure why you'll want that, but maybe you can try this?

module ActiveRecord
  class Base
    def self.your_method
      # implementation goes here
    end
  end
end

You will need to save this file and put it in config/intializers.

Upvotes: 5

Related Questions