dlu
dlu

Reputation: 791

Aliasing model names in Rails

I'm working on the design of an application in which there will be users with two (not necessarily distinct) roles, teachers and students. So, I'm thinking I'd have one User class with associated roles.

To make the code (hopefully) more readable, I'd like to refer to instances of the User class by an alias where the role is required. For example if the user must have the role of student I'd like to do something like this:

class Section < ActiveRecord::Base
  alias :user :student
  alias :user :teacher

  belongs_to :teacher
  has_many :students
end

Is there a way to do something like this?

Upvotes: 1

Views: 720

Answers (3)

Abhishek Kumar
Abhishek Kumar

Reputation: 694

You can do

class Section < ActiveRecord::Base
  belongs_to :teacher, :class_name => "Section", :foreign_key => "teacher_section_id"
  has_many :students, :class_name => "Section", :foreign_key => "teacher_section_id"
end

Answer copied from: rails model has_many of itself

EDIT:

How are you going to differentiate a Teacher from a user? I think you should make a column(section_type) in Section table for that. And then you can create scopes like

class Section < ActiveRecord::Base
  belongs_to :teacher,-> {where("section_type == 'teacher'")} ,:class_name => "Section", :foreign_key => "teacher_section_id"
  has_many :students, -> {where("section_type == 'students'")},:class_name => "Section", :foreign_key => "teacher_section_id"
end

Upvotes: 1

J Plato
J Plato

Reputation: 898

If I understand correctly what you're trying to do, you would subclass User as follows:

class Teacher < User
end

class Student < User
end

and use the belongs_to and has_many associations exactly as you have them in Section.

Upvotes: 1

errata
errata

Reputation: 26822

If you are dealing with roles you might want to have a look at the Rolify gem. It's very simple and has documentation that will show you some common approaches to dealing with roles. The methods above seem a little unconventional, which may suit your use case but I have had great luck with Rolify for fairly large apps.

https://github.com/RolifyCommunity/rolify

Upvotes: 1

Related Questions