Self-referential has_many :through association don't work because it doesn't use the correct foreign key to get back to the original table. The attached patch with tests allows the :association_foreign_key option to be set for has_many :through relationships and uses that value in its joins.
This will enable something like the following:
class Post < ActiveRecord::Base
has_many :related_post_infos, :class_name => 'RelatedPost'
has_many :related_post, :class_name => 'Post', :through => :related_post_infos, :association_foreign_key => 'related_post_id'
end
class RelatedPost < ActiveRecord::Base
belongs_to :post
belongs_to :related_post, :class_name => 'Post', :foreign_key => 'related_post_id'
acts_as_list :scope => 'post_id'
end
Currently Post.find(1).related_posts will result in this query:
SELECT posts.* FROM related_posts, posts WHERE (posts.id = related_posts.post_id AND related_posts.post_id = 1)
when it should be:
SELECT posts.* FROM related_posts, posts WHERE (posts.id = related_posts.related_post_id AND related_posts.post_id = 1)