Skip to content

Instantly share code, notes, and snippets.

@timdorr
Created November 25, 2013 19:38
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save timdorr/7647415 to your computer and use it in GitHub Desktop.
Save timdorr/7647415 to your computer and use it in GitHub Desktop.
A basic self-referential friendship model in Rails 4.0.1
class Friendship < ActiveRecord::Base
belongs_to :user
belongs_to :friend, class_name: "User"
end
2.0.0p247 :002 > u = User.create!(name:"test")
(0.4ms) BEGIN
SQL (44.1ms) INSERT INTO "users" ("created_at", "name", "updated_at") VALUES ($1, $2, $3) RETURNING "id" [["created_at", Mon, 25 Nov 2013 19:35:06 UTC +00:00], ["name", "test"], ["updated_at", Mon, 25 Nov 2013 19:35:06 UTC +00:00]]
(0.8ms) COMMIT
=> #<User id: 1, name: "test", created_at: "2013-11-25 19:35:06", updated_at: "2013-11-25 19:35:06">
2.0.0p247 :003 > u.friends
User Load (2.2ms) SELECT "users".* FROM "users" INNER JOIN "friendships" ON "users"."id" = "friendships"."friend_id" WHERE "friendships"."user_id" = $1 [["user_id", 1]]
=> #<ActiveRecord::Associations::CollectionProxy []>
class CreateFriendships < ActiveRecord::Migration
def change
create_table :friendships do |t|
t.integer :user_id
t.integer :friend_id
t.timestamps
end
end
end
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :name
t.timestamps
end
end
end
class User < ActiveRecord::Base
has_many :friendships
has_many :friends, through: :friendships
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment