egervari
egervari

Reputation: 22512

How can use rails polymorphic for objects that actually have fields?

Let's say I have a User model and I want to have different user roles. In a single application, you can simple store the role a string, or as another model and that's fine.

But what if you want to store more associations for the individual models? For example, let's say Admins contain links to collections and belongs to many collections that regular users should not be associated to? In fact, other users will be linked to a whole other set of models that Admins do not have.

Do we put all of the associations in the User object and just ignore them based on the type of the user? Or do we start subclassing User (like in Hibernate) to only contain the associations and model logic for that user type?

What is the way to do this in rails? Thanks!

Upvotes: 1

Views: 144

Answers (1)

Mike Trpcic
Mike Trpcic

Reputation: 25649

I would suggest using Rails Single Table Inheritance. Essentially, you'll have a users table in your database, and a root User model. Multiple models (one for each "role") can inherit from User, and have their own associations:

# Regular users have no associations
class User < ActiveRecord::Base
end

# Admins have collections and notes
class Admin < User
  has_many :collections
  has_many :notes
end

# Editors only have notes
class Editor < User
  has_many :notes
end

Upvotes: 1

Related Questions