ruby on rails - Compare associations on different ActiveRecords without fetching from the DB -
i able compare associated records on activerecords, without fetching database. following comparison, hits db when make comparison
employee1 = employee.find_by(name: 'alice') debug employee load (92.0ms) select "employees".* "employees" "employees"."name" = 'alice' limit 1 employee2 = employee.find_by(name: 'bob') debug employee load (92.0ms) select "employees".* "employees" "employees"."name" = 'bob' limit 1 employee1.manager == employee2.manager debug employee load (697.9ms) select "employees".* "employees" "employees"."id" = $1 order "employees"."id" asc limit 1 [["id", 53]] debug employee load (504.1ms) select "employees".* "employees" "employees"."id" = $1 order "employees"."id" asc limit 1 [["id", 53]] => true
i can compare values of foreign columns directly, that's less idiomatic , can difficult refactor later on:
employee1.manager_id == employee2.manager_id => true
edit: i've added own answer solution question below
if know you're going needing/using manager
employee
during operation, can make sure load object when employee loaded, prevent trip database:
employee1 = employee.includes(:manager).find_by(name: 'alice') employee2 = employee.includes(:manager).find_by(name: 'bob') employee1.manager == employee2.manager => true # database hit not needed...
that or compare ids, make helper method on employee like
class employee def same_manager?(other_employee) other_employee.manager_id == self.manager_id end end
at least way it's given name , operation within makes sense in context.
Comments
Post a Comment