Skip to content

Instantly share code, notes, and snippets.

@danshultz

danshultz/code.rb

Created Nov 8, 2012
Embed
What would you like to do?
Reply to Blog post activerecord-black-magic
# Ref http://spin.atomicobject.com/2012/10/30/activerecord-black-magic/
class EmployeeFinder
def self.accessible_by(user)
Employee.joins(:companies) \
.merge(Company.where(:id => user.company_ids)) \
.uniq
end
end
UploadedFile.where(uploaded_by: EmployeeFinder.accessible_by(user))
# Alternately, you could also do this and I think most explain plans will find it more effective
class EmployeeFinder
def self.accessible_by(user)
filter = Employee \
.joins(:companies) \
.merge(Company.where_company([1,4])) \
.select(Employee.arel_table[:id])
Employee.where(:id => filter)
end
end
# SQL output
>> UploadedFile.by_employees(EmployeeFinder.accessible_by(user))
UploadedFile Load (0.3ms) SELECT "uploaded_files".* FROM "uploaded_files" WHERE "uploaded_files"."employee_id" IN (SELECT "employees"."id" FROM "employees" WHERE "employees"."id" IN (SELECT "employees"."id" FROM "employees" INNER JOIN "companies_employees" ON "companies_employees"."employee_id" = "employees"."id" INNER JOIN "companies" ON "companies"."id" = "companies_employees"."company_id" WHERE "companies"."id" IN (1, 4)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.