[Rails] Multiple foreign keys (and an introduction)

Jarkko Laine jarkko at jlaine.net
Sat Feb 26 20:35:36 GMT 2005


On 26.2.2005, at 22:07, Adam Fields wrote:

>
> Hi - I've just picked up rails, and obviously finding a lot to like.
>
> I've searched the archives and looked at the docs for Active Record,
> but I'm not sure if I'm conceptually approaching this the right way. I
> know how I'd build it from scratch.
>
> My question is this -
>
> What's the right way to deal with a table that models relationships
> with multiple foreign keys into the same parent table?
>
> So, say I have two tables, "authors" and "articles". "authors" is a
> simple collection of people. Now, suppose that an article has three
> authors - "original_author", "last_author" and "supervising_author",
> all of which are foreign keys via author_id.
>
> Any suggestions on modeling this with rails? Do I need to make
> subclasses of author and use those as placeholders for the different
> "author types"?

Class Article < ActiveRecord::Base
	belongs_to :original_author, :class_name => "Author", :foreign_key => 
"orig_author_id"
	belongs_to :last_author, :class_name => "Author", :foreign_key => 
"last_author_id"
	belongs_to :supervising_author, :class_name => "Author", :foreign_key 
=> "sup_author_id"
end

Then put those foreign key fields to your articles table.

If you need to reach articles from the Author's direction, you also 
have to add corresponding has_many lines to your Author class, like 
this:
	has_many :original_articles, :class_name => "Article", :foreign_key => 
"orig_author_id"

//jarkko

>
> Thanks!
>
> -- 
> 				- Adam
>
> -----
> ** My new project --> http://www.visiognomy.com/daily
>    **  Flagship blog --> http://www.aquick.org/blog
> Hire me: [ http://www.adamfields.com/Adam_Fields_Resume.htm ]
> Links:   [ http://del.icio.us/fields ]
> Photos:  [ http://www.aquick.org/photoblog ]
>
>
> _______________________________________________
> Rails mailing list
> Rails at lists.rubyonrails.org
> http://lists.rubyonrails.org/mailman/listinfo/rails
>
--
Jarkko Laine
http://jlaine.net
http://odesign.fi
-------------- next part --------------
A non-text attachment was scrubbed...
Name: smime.p7s
Type: application/pkcs7-signature
Size: 2363 bytes
Desc: not available
Url : http://one.textdrive.com/pipermail/rails/attachments/20050226/2c871de5/smime.bin


More information about the Rails mailing list