Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial


Tricky Models/Associations problem

I have a User model and a Teacher model that inherits from the User model.

The User table has a column called :admin with a boolean value. This allows me to set any User as an admin (via the Rails console: 'User.find.(2).update_attributes(admin: true)'.

I want to create a Materials model.

This would be simple if it was only relevant to, say, just Teachers. I would then have a simple Teachers has_many :materials and Materials belongs_to :teacher.

However, I want any admin to access and post to a 'master' Materials page...

...and I want each Teacher to have their own 'Materials' page that they can post to AND....

I want Teachers to be able to go to the 'master' Materials page and select Materials from that page to also appear on their own Materials page.

After much deliberation, I think I need to have Materials has_many_and_belongs_to :users and ALSO belongs_to :user.

I'm not sure how to go about this, but I think something like this might be a solution: http://stackoverflow.com/questions/13959955/belongs-to-and-has-and-belongs-to-many-to-the-same-table-in-rails

Am I barking up the wrong tree? What do you think?

Might need a staff to help me on this one? Jason Seifer ?

Another potentially tricky aspect, is that I would want all the Materials on a Teacher's Materials page to be listed chronologically (by date of creation), even when that list contains Materials from the Admins' Materials page.

Maciej Czuchnowski
Maciej Czuchnowski
36,441 Points

Is your inheritance necessary? It complicates a lot :).

It does in this instance, but up to now it's been beneficial. Users sign up to the site and then admins can assign them to be Teachers or Students (a form changes Users' :type column value to "Student" or "Teacher" and quite a lot of the site's functionality is based off that, so I'm quite reluctant to change that now.

Maciej Czuchnowski
Maciej Czuchnowski
36,441 Points

In the future, consider using the enum feature introduced in Rails 4.1. An example here: https://gustavocguimaraes.wordpress.com/2014/12/17/role-based-authorization-with-rails-4-enum/

It's very handy and flexible and does not require any additional models. You can combine this with a separate admin boolean for more fine-grained control.