Larry M
Larry M

Reputation:

ActiveRecord Inheritance with Different Database Tables

I have just started investigating using more advanced models in Rails. One that I use regularly, with great success, is model where a many-to-many cross-reference relationship is accessed by a class that itself is a sub-class of the base class in the many-to-many relationship.

This way the cross-reference class can act as a stand-in for the base class.

A good example is where a navigation hierarchy node (NavigationNode) is cross-referenced to a user role. At the cross-reference point a class (RoleNavigationNode) can inherit from NavigationNode and still have intimate knowledge of the user role.

My question is (in the case above) can RoleNavigationNode inherit from NavigationNode and yet access the cross-reference table rather than the one that NavigationNode accesses -- this of course using ActiveRecord.

I have not investigated polymorphic association, which may be more appropriate.

Thanks in advance...,

Upvotes: 3

Views: 1147

Answers (2)

benzado
benzado

Reputation: 84408

This works in Rails 3:

class Common < ActiveRecord::Base
  @abstract_class = true
  def common
    "Foobar!"
  end
end

class Model < Common
end

class AnotherModel < Common
end

Without setting abstract_class, Rails will look for a table named commons in your database.

Upvotes: 2

kch
kch

Reputation: 79670

tried set_table_name on the subclass?

Also, look into setting @abstract_class in model classes.

Lastly, what you need may simply be a Mixin that you include in both models.

Anyway, what you're trying to do sounds rather un-ActiveRecord-ish. You might want to post a clearer example of what you're trying to achieve, maybe we'll be able to come up with something simpler.

Upvotes: 2

Related Questions