Skip to content

Instantly share code, notes, and snippets.

@invalidusrname
Last active April 3, 2019 21:13
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 invalidusrname/34ce4be2c9f3af0159e77333d5bf1dee to your computer and use it in GitHub Desktop.
Save invalidusrname/34ce4be2c9f3af0159e77333d5bf1dee to your computer and use it in GitHub Desktop.
Owned Sites
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
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