Re: conditional association

Rick DeNatale
Sun, 27 Jan 2008 14:12:50 -0000

On 1/27/08, Gregory Seidman
<gsslist+ror-dNXPQ6k9rNiG6BJUYyje5axOck334EZe@public.gmane.org>
wrote:
>
> On Sun, Jan 27, 2008 at 10:29:06AM +0000, Frederick Cheung wrote:
> > On 27 Jan 2008, at 03:58, AD wrote:
> > >  i have an association as follows.  A user is of type
"author" or
> > > "reader".  In the user table is a column called
user_type_id that
> > > references a user_type table of 2 records, author, reader.  What
i
> > > am trying to do is the following:
> > >
> > >  Create an association such that a user has_one :profile, but
> > > the :profile is either author_profile table or reader_profile
table
> > > (they have too many different attributes to make one profile
table)
> > > depending on the user type.  is there a way to specify a
conditional
> > > has_one in the user model that would allow access to
''user.profile''
> > > but know which model to reference ?  Either that or do a
conditional
> > > set_table_name depending on a variable ..
> > >
> > Perhaps a polymorphic association ? Or alternatively use STI, and have
> > a base class User with the common functionality and both Author and
> > Read inheriting from that. Then it''s easy, because you just
stick
> > has_one :author_profile in Author and has_one :reader_profile in
Reader.
>
> Yep, I was going to suggest STI. This is exactly the sort of situation for
> which it is appropriate.

Well, it depends on how much the Author and Reader models have in
common, as to whether it makes sense to use STI, i.e. how many
attributes they have in common.

If it distorts reality too much to force them to use a single table,
then a polymorphic association is probably the better approach.

--
Rick DeNatale

My blog on Ruby