-
If needing to filter out records from an
ActiveRecord_AssociationRelation
object- use an ActiveRecord Query Interface method e.g.
.where
,.joins
- see Understanding the difference between where and select in Rails
-
The bottom line is that we should always use .where rather than .select to improve the speed and save the memory of the application.
-
e.g.
# bad # Co Pilot example removal_child.children_groups.select { |child| child.id != removal_child.id } # my example removal_child.children_groups.filter { |child_group| child_group.group.present? } #good # Co Pilot example removal_child.children_groups.where.not(id: removal_child.id) # my example removal_child.children_groups.joins(:group) .where.not(group_id: existing_child.children_groups.map(&:group_id))
- use an ActiveRecord Query Interface method e.g.
If needing to filter out records from an ActiveRecord_AssociationRelation
object, use where
instead of select
to avoid loading the records into
memory.
From chat with Mat:
- levels of understanding
- some cases it is better to load everything in memory, and then use select
- need to have data there for mutiple reasons
e.g.
- current user in system
- load all relations and then do select to find admin relations children
- media in stories or com posts - media items, select, documents! on com posts