Hi all,
I found what I think is a slick solution to a problem of mine but I'd like to know if there is a better way to accomplish what I did.
I have 2 tables:
Users: id category # can be either 'ADMIN', 'AUDITOR' or 'TENANT'
Audits: id auditor_id tenant_id
I need the audits to belong to both an AUDITOR and a TENANT user:
class User < ActiveRecord::Base has_many :audits end
class Audit < ActiveRecord::Base belongs_to :user # !!! This does not work even using :class_name, etc. !!! end
After tinkering for a while with it I couldn't find an easy way of making it work. Then I had an idea that has worked and I think is pretty slick. I created 3 models:
class Admin < User # Admin specific functionality here end
class Auditor < User has_many :audits # Auditor specific functionality here end
class Tenant < User has_many :audits # Tenant specific functionality here end
When a user is retrieved for access and functionality validations, I re-retrieve the user through the specific user class as in: user = User.find(...) # The user is found and passes validations. # Now I re-retrieve it through the specific user class based in the category value. user = user.category.capitalize.constantize.find(user.id) if user
From that moment on I have the user retrieved through its correct type and my associations work wonderfully.
Is there a better way of making this work?
Thanks.
Pepe