Adam,
On 2.9.2005, at 9.32, Adam Roth wrote:
> Is it possible for Rails to indentify a belongs_to_and_has_many
> style relationship without the use of mapping tables?
>
> IE:
>
> * We have ''friends'', ''places'', and
''pics''.
> * There can be N pics of ''friends''
> * There can be N pics of ''places''
>
> table: friends
> table: places
> table: pics
>
> Pics Table:
>
> id | type | type_id | filename
>
> 0 friend 1 friend1.jpg
> 1 friend 2 friend2.jpg
> 2 place 1 place1.jpg
> 3 friend 3 friend3.jpg
>
> Where ''type'' corresponds to the object that has pics
(friends or
> places), and ''type_id'' is it''s primary key.
This is not a many-to-many relationship. In this scheme, a pic can
only be related to one friend/place so it''s one-to-many. If
that''s
ok, fine, but then you also don''t need has_and_belongs_to_many, you
need has_many/belongs_to.
>
> Right now I have the current setup, which works...
>
> table: friends
> table: places
> table: pics
> table: friends_pics
> table: pics_places
>
> but I was curious to see if it could be done automagically with a
> type/type_id column in the pics table.
If a one-to-many relationship is fine, you can use single-table
inheritance for this. However, you probably shouldn''t use it in the
places/friends end because they would need to be stored in a single
table and they probably have pretty different characteristics.
So what you could use is have two different kinds of pics that would
both use the pics table. However, it would need to have two foreign
key fields, one to friends and one to places table. So even it would
actually be just what you described. But anyway, a foreign key field
should always reference just one table so your type_id field idea is
considered pretty bad practice in db circles.
Try googling for single table inheritance in Rails for more info
about it. Probably the best take on it is (not surprisingly) in the
Rails book [1].
//jarkko
[1] http://www.pragmaticprogrammer.com/titles/rails/index.html
>
> Thanks
> Adam
>
>
>
>
> _______________________________________________
> Rails mailing list
> Rails-1W37MKcQCpIf0INCOvqR/iCwEArCW2h5@public.gmane.org
> http://lists.rubyonrails.org/mailman/listinfo/rails
>
--
Jarkko Laine
http://jlaine.net
http://odesign.fi
_______________________________________________
Rails mailing list
Rails-1W37MKcQCpIf0INCOvqR/iCwEArCW2h5@public.gmane.org
http://lists.rubyonrails.org/mailman/listinfo/rails