Select values through many to many relationship in active record
This is my memo on Select values through many to many relationship in active record.
Query for grandchildren, through a many to many relationship
I want to obtain all the tags that have a household item belonging to a specific moving, through a many to many relationship.
Tag.joins(household_items: :moving)
.where(movings: {id: id})
.select('DISTINCT tags.name')
.order('tags.name')
# This works but it requires n queries.
household_items.map { |item| item.tags }.flatten.map(&:name).uniq
Select values through many to many relationship in active record using “where”