Forum: Ruby on Rails custom foreign key field

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
F15fdc7cb2e911b3808837f2be244add?d=identicon&s=25 straightflush (Guest)
on 2005-11-20 17:08
(Received via mailing list)
I have 3 tables, news,activities, threads.

  threads contains all the replies for news and activities.  Therefore
threads has a category_id  and postid column to map a reply to a table
and initial thread.

 How do i say that news has many threads, but threads has a generic
post_id foreign key field, not a news_id foreign key field as well as
a category_id of 1 (or 2 if its activities)?

thanks
adam
Eea3feaacbe44706164289d068d94828?d=identicon&s=25 petermichaux (Guest)
on 2005-11-20 20:14
(Received via mailing list)
Hi Adam,

I'll take a guess that you want to do this:

-news
id serial
body_text text

-activities
id serial
body_text text

-replies
id serial
owner_class varchar(255)
owner_id int
body_text text



Class News < ActiveRecord::Base
has_many :replies,
:foreign_key => "owner_id"
:conditions => "owner_class = 'News'"
:order => 'id'
end

Class Activities < ActiveRecord::Base
has_many :replies,
:foreign_key => "owner_id"
:conditions => "owner_class = 'Activities'"
:order => 'id'
end

Class Replies < ActiveRecord::Base
end


I am doing exactly this for images in store.rb project. If someone has a
better idea I'd like to hear it too!

Peter
A2c85dc5ee81b12e3cc0a6522e8d079d?d=identicon&s=25 christopher.k.hall (Guest)
on 2005-11-20 20:35
(Received via mailing list)
why not just use single table inheritance?

posts
----------
id
type (magic column name)
body

replies
----------
id
post_id
body

class Post < ActiveRecord::Base
end

class NewsPost < Post
has_many :replies
end

class Article < Post
has_many :replies
end

class Reply < ActiveRecord::Base
belongs_to :post
end

news_post = NewsPost.create("foobar")
news_post.replies << Reply.create("barfoo")

post = Post.find(:first) # post == NewsPost object
Eea3feaacbe44706164289d068d94828?d=identicon&s=25 petermichaux (Guest)
on 2005-11-20 20:59
(Received via mailing list)
Could this all be in just one table since posts and replies are so
similar?
I haven't used single table inheritance before but maybe something like
this
will work?

posts
----------
id
type (magic column name: News, Article, Reply)
body
parent_id

class Post < ActiveRecord::Base
acts_as_tree
end

class News < Post
end

class Article < Post
end

class Reply < Post
end

A new thread (either News or Article) will have parent_id NULL.
This topic is locked and can not be replied to.