ActiveRecord::QueryMethods 中 joins 的一种用法

要根据一个 role,找到所有 user。

class User < ActiveRecord::Base
  has_many :members
  has_many :roles, through: :members

  scope :by_role, ->(role) { joins(:roles).where( roles: { id: role }) }
end

class Member < ActiveRecord::Base
  belongs_to :user
  has_many :member_roles
  has_many :roles, through: :member_roles
end

class MemberRole < ActiveRecord::Base
  belongs_to :role
  belongs_to :member
end

class Role < ActiveRecord::Base
end

查询可以这样

User.by_role(2).to_sql

生成的 SQL

"SELECT "users".* FROM "users" INNER JOIN "members" ON "members"."user_id" = "users"."id" INNER JOIN "member_roles" ON "member_roles"."member_id" = "members"."id" INNER JOIN "roles" ON "roles"."id" = "member_roles"."role_id" WHERE "roles"."id" = 2"

也可以改成

class User < ActiveRecord::Base
  has_many :members

  scope :by_role, ->(role) { joins(members: :roles).where( roles: { id: role }) }
end

如果觉得我的文章对您有用,请在支付宝公益平台找个项目捐点钱。 @Victor Sep 9, 2014

奉献爱心