You can try something on these lines too

class User < ActiveRecord::Base
  has_many :audits_as_auditor, :class_name => 'Audit', :foreign_key =>
'auditor_id'
  has_many :audits_as_tenant, :class_name => 'Audit', :foreign_key =>
'tenant_id'
end

Pradeep

On Jul 13, 11:07 am, Jitu <[email protected]> wrote:
> Have you tried,
>
> class Audit < ActiveRecord::Base
>   belongs_to :auditor, :class_name => 'User', :foreign_key =>
> 'auditor_id'
>   belongs_to :tenant,  :class_name => 'User', :foreign_key =>
> 'tenant_id'
> end
>
> class User < ActiveRecord::Base
>   has_many :auditors
>   has_many :tenants
> end
>
> On Jul 12, 9:43 pm, pepe <[email protected]> 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 [email protected]
To unsubscribe from this group, send email to 
[email protected]
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to