Topic: Help with associations: User, Lecturer, Student and Event

Hi everyone,

I've googled, read the docs, and watched railscast, but I can't wrap my head around this.
Please help. I'm running the latest stable Rails and Ruby 1.9.3, on Ubuntu 13.04.

I have a User model, and an Event model.
Right now, there is a has_and_belongs_to_many relationship between the two.

In real life, however, a User relates to the Event as either a Lecturer or a Student.
A User can be both a Student and Lecturer, but not for the same event.
Lecturer or Student are not yet models in my app, and I'm unsure if they should be separate models.

I need help with implementing this logic.

What I want to achieve is something like this:

Event.first.lecturers # Should return Users that are Lecturers for this particular Event.

Event.first.students # Should return Users that are Students for this particular Event

User.first.events :as => :student # Should return Events for a particular User where the User is a Student

User.first.events :as => :lecturer # Should return Events for a particular User where the User is a Lecturer

I'm thinking perhaps a has_many :through association might work, but I'm so confused.

Any and all guidance appreciated.

Regards,

Nadeem

Re: Help with associations: User, Lecturer, Student and Event

You can have one model - User, to define al kind of whatever you want. I'd just add an attribute:
- either 'type' (reserved word for STI !)  and use STI (single table inheritance)
- or 'user_type' that should be chosen when creating a user: either Lecturer or Student.

Then, depending on what solution you'll choose, STI or not, you can get Students or Lecturer like that:

- either by creating scope method n User model to get (Lecturers or Students only)
- or with STI it goes out of the box when calling:

Event.first.lecturers #to get lecturers
Event.first.students #to get students

See more details here: http://api.rubyonrails.org/classes/Acti … /Base.html

Hope this helps