Last active
April 3, 2019 21:13
-
-
Save invalidusrname/34ce4be2c9f3af0159e77333d5bf1dee to your computer and use it in GitHub Desktop.
Owned Sites
This file contains hidden or 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 < ApplicationRecord | |
has_many :site_users, dependent: :destroy | |
has_many :sites, through: :site_users | |
def owned_sites | |
sites.where("site_users.roles_mask = ?", SiteUser.mask_for(:owner)) | |
end | |
def owned_sites_using_includes | |
sites.includes(:site_users).where("site_users.roles_mask = ?",SiteUser.mask_for(:owner)) | |
end | |
end |
This file contains hidden or 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
irb(main):003:0> User.first.owned_sites.all | |
User Load (0.2ms) SELECT "users".* FROM "users" ORDER BY "users"."id" ASC LIMIT ? [["LIMIT", 1]] | |
Site Load (0.2ms) SELECT "sites".* FROM "sites" INNER JOIN "site_users" ON "sites"."id" = "site_users"."site_id" WHERE "site_users"."user_id" = ? AND (site_users.roles_mask = 16) LIMIT ? [["user_id", 1], ["LIMIT", 11]] | |
=> #<ActiveRecord::AssociationRelation [#<Site id: 1, name: "ok", created_at: "2019-04-02 18:40:23", updated_at: "2019-04-02 18:40:23">]> | |
irb(main):004:0> User.first.owned_sites_using_includes.all | |
User Load (0.1ms) SELECT "users".* FROM "users" ORDER BY "users"."id" ASC LIMIT ? [["LIMIT", 1]] | |
Site Load (0.1ms) SELECT "sites".* FROM "sites" INNER JOIN "site_users" ON "sites"."id" = "site_users"."site_id" WHERE "site_users"."user_id" = ? AND (site_users.roles_mask = 16) LIMIT ? [["user_id", 1], ["LIMIT", 11]] | |
SiteUser Load (0.1ms) SELECT "site_users".* FROM "site_users" WHERE "site_users"."site_id" = ? [["site_id", 1]] | |
=> #<ActiveRecord::AssociationRelation [#<Site id: 1, name: "ok", created_at: "2019-04-02 18:40:23", updated_at: "2019-04-02 18:40:23">]> | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment