Skip to content

Instantly share code, notes, and snippets.

@KatagiriSo
Created November 25, 2015 02:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KatagiriSo/26695dc77f67023d7c43 to your computer and use it in GitHub Desktop.
Save KatagiriSo/26695dc77f67023d7c43 to your computer and use it in GitHub Desktop.
railsの多対多関連の例
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