Created
November 25, 2013 19:38
-
-
Save timdorr/7647415 to your computer and use it in GitHub Desktop.
A basic self-referential friendship model in Rails 4.0.1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Friendship < ActiveRecord::Base | |
belongs_to :user | |
belongs_to :friend, class_name: "User" | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 []> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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