That was an interesting question.
I just created a working app for your use case.
post.related_posts will give you all posts related from post, while post.inverse_related_posts will give you all posts related to post.
Here's what my models look like:
class Post < ActiveRecord::Base
has_many :related_posts_association, :class_name => "RelatedPost"
has_many :related_posts, :through => :related_posts_association, :source => :related_post
has_many :inverse_related_posts_association, :class_name => "RelatedPost", :foreign_key => "related_post_id"
has_many :inverse_related_posts, :through => :inverse_related_posts_association, :source => :post
end
class RelatedPost < ActiveRecord::Base
belongs_to :post
belongs_to :related_post, :class_name => "Post"
end
My schema:
ActiveRecord::Schema.define(:version => 20110702194300) do
create_table "posts", :force => true do |t|
t.string "name"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "related_posts", :force => true do |t|
t.integer "post_id"
t.integer "related_post_id"
t.datetime "created_at"
t.datetime "updated_at"
end
end
Here's a dump of a console session that demonstrating the relationship.
ruby-1.9.2-p180:001:0>> p = Post.create! name: "Hello"
SQL (23.5ms) INSERT INTO "posts" ("created_at", "name", "updated_at") VALUES (?, ?, ?) [["created_at", Sat, 02 Jul 2011 20:03:43 UTC +00:00], ["name", "Hello"], ["updated_at", Sat, 02 Jul 2011 20:03:43 UTC +00:00]]
# => #<Post id: 1, name: "Hello", created_at: "2011-07-02 20:03:43", updated_at: "2011-07-02 20:03:43">
ruby-1.9.2-p180:002:0>> p2 = Post.create! name: "World"
SQL (1.0ms) INSERT INTO "posts" ("created_at", "name", "updated_at") VALUES (?, ?, ?) [["created_at", Sat, 02 Jul 2011 20:03:48 UTC +00:00], ["name", "World"], ["updat
answered 2011-07-02T20:10:35.653