daniel barrera
daniel barrera

Reputation: 367

Inheritance of models in Ruby on Rails

I have 2 or more models that have a method in common called CapitalizeEachWord.

Can I access the class ActiveRecord::Base and paste the method inside? or create a model called Application that inherits the ActiveRecord::Base directly and then to do that BreakPoint and BusCompany inherit from it?

       class BreakPoint < ActiveRecord::Base
          attr_accessible :city,:province_id,:province
          belongs_to :province
          before_save :capitalizeEachWord
          validates :city, presence: true,
                           uniqueness: true,
                           format: /^([[:alpha:]]+\s?){1,}$/
          def capitalizeEachWord
           self.city=self.city.downcase.split.map(&:capitalize).join(' ')
          end              
        end

       class BusCompany < ActiveRecord::Base
         attr_accessible :company
         has_many :bus_set_types 
         validates :company, presence: true, 
                      uniqueness: true,
                      format:  /^([[:alpha:]]+\s?){1,}$/

         def capitalizeEachWord
           self.name=self.name.downcase.split.map(&:capitalize).join(' ')
         end
       end

Upvotes: 0

Views: 57

Answers (3)

Dan Bradbury
Dan Bradbury

Reputation: 2116

The way that I've seen this work best is very similar to your second idea.

Create a ApplicationModel < ActiveRecord::Base and go ahead and add any shared logic in there.

With this approach your other models will look something like this (OauthProvider < ApplicationModel) and include any functionality that you put into the ApplicationModel.

Upvotes: 1

BarFooBar
BarFooBar

Reputation: 1136

You can't modify ActiveRecord::Base without some significant hacking endeavors.

What you're probably looking for is a decorator. Decorators are a common design pattern that allows you to add functionality to an object dynamically without having to make static subclasses.

This Code Climate Blog lets you know how to do it in Rails: Refactoring Fat Models

If you're interested in some other ways to do this with plain Ruby (eg modules and mixins) check out this ThoughtBot article.

Upvotes: 1

TK-421
TK-421

Reputation: 10763

I'd suggest your second option.

(A more advanced option would be to store it outside of an AR-derived class, as it is somewhat more generally applicable, but that might be too much effort in this case. You could always extract it later, if necessary.)

Upvotes: 1

Related Questions