Yes - check out the Rails docs for discussion of Single-Table Inheritance. The major change will be that your 'category' column will be renamed to 'type', and you'll be able to skip the second find step.
--Matt Jones On Jul 12, 10:43 am, pepe <p...@betterrpg.com> wrote: > 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 --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group. To post to this group, send email to rubyonrails-talk@googlegroups.com To unsubscribe from this group, send email to rubyonrails-talk+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en -~----------~----~----~----~------~----~------~--~---