Created
November 25, 2015 02:45
-
-
Save KatagiriSo/26695dc77f67023d7c43 to your computer and use it in GitHub Desktop.
railsの多対多関連の例
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 | |
# SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 | |
has_many :messages | |
#フォロー関連 | |
# SELECT "followmaps".* FROM "followmaps" WHERE "followmaps"."user_id" = ? | |
# user_idに紐づくFollowmapの情報を取得 | |
has_many :followmaps, class_name: "Followmap", foreign_key: :user_id | |
#SELECT "users".* FROM "users" INNER JOIN "followmaps" ON "users"."id" = "followmaps"."follow_id" WHERE "followmaps"."user_id" = ? | |
# user_idに紐づくFolowmapを通してfollow_idに対応するユーザを取り出す。 | |
has_many :follows, through: :followmaps | |
#フォロワー関連 | |
has_many :followermaps, class_name: "Followmap", foreign_key: :follow_id | |
has_many :followers, through: :followermaps | |
end | |
class Followmap < ActiveRecord::Base | |
#User側のfollowsと対応している。 | |
belongs_to :follow, class_name: "User", foreign_key: :follow_id | |
#User側のfollowersと対応している。 | |
belongs_to :follower, class_name: "User", foreign_key: :user_id | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment