Skip to content

Instantly share code, notes, and snippets.

@srpouyet
Last active November 2, 2019 03:05
Show Gist options
  • Save srpouyet/4121517 to your computer and use it in GitHub Desktop.
Save srpouyet/4121517 to your computer and use it in GitHub Desktop.
Self referential HABTM (has_and_belongs_to_many) in Rails 3
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.timestamps
end
end
end
class User < ActiveRecord::Base
# attr_accessible :title, :body
# HABTM Self referential relationship seems to be working with custom finder_sql
has_and_belongs_to_many :related_users,
class_name: 'User',
join_table: :related_users,
foreign_key: :user_id,
association_foreign_key: :related_user_id,
uniq: true,
finder_sql: proc { %(SELECT DISTINCT "users".* FROM "users"
INNER JOIN "related_users" ON "users"."id" = "related_users"."related_user_id"
WHERE "related_users"."user_id" = #{self.id}
UNION
SELECT DISTINCT "users".* FROM "users"
INNER JOIN "related_users" ON "users"."id" = "related_users"."user_id"
WHERE "related_users"."related_user_id" = #{self.id} )}
end
@srpouyet
Copy link
Author

TODO: It's possible to add the same associations multiple times, some custom :insert_sql should be added to fix this.

@andriytyurnikov
Copy link

add_index should be within the body of change method, isn't it? :)

@srpouyet
Copy link
Author

srpouyet commented Mar 6, 2013

@andriytyurnikov I think you're right, I'll update the gist. Cheers!

@faustman
Copy link

faustman commented Apr 4, 2013

if a I call user.related_users.limit(2), activerecord ignores my finder_sql SQL statement. Its a bug? Rails 3.2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment