0

I have the following HABTM relation and corresponding logic that is identical in at least 3 different tables, so I wanted to factor it, and related methods, into a common base class. The problem is, even though the association does show up in the object's association_cache, trying to access it results in an exception (ArgumentError comparison of nil object with a string). I'm confused about why this isn't working, as this seems like basic OOP programming.

My base model is set up like this:

class ProfileItem < ActiveRecord::Base
  self.abstract_class = true
  has_and_belongs_to_many :profiles
  attr_accessor :profile_ids
  before_destroy :clean_up
  before_save :update_profiles

def get_profile_names
  self.profiles.each do |p|  # << exception here
  ...
dev-null
  • 3
  • 1
  • By the way, about half of the code I was refactoring out of my base classes was related to managing the many-to-many relationship. (e.g. notice my attr_accessor :profile_ids.) I discovered that Rails manages most of this "automagically" for you. All I had to do was add id's to that array (which Rails exposed all ready) and add that array to my "allows' clause in the controller. – dev-null May 20 '14 at 17:17

1 Answers1

0

Look into a concept called concerns, introduced in Rails 4. Abstracting a class inherited from ActiveRecord::Base is a recipe for trouble.

A good explanation How to use concerns in Rails 4.

Community
  • 1
  • 1
Eyeslandic
  • 14,553
  • 13
  • 41
  • 54
  • 1
    I re-refactored my code, and using concerns worked indeed. It makes me kind of sad to have to resort to something like this in what is an otherwise very elegant object oriented language. – dev-null May 20 '14 at 17:10
  • Another possibility is using models http://stackoverflow.com/questions/11178988/how-to-share-validations-accros-models – Eyeslandic May 20 '14 at 18:07
  • I presume you meant "modules". I'm not sure what the difference is between a concern and a module. What I'd really like to do is use inheritance, but since that isn't possible, I'll make due with concerns. I wish someone could explain why this doesn't work, though. – dev-null May 21 '14 at 00:51