Masatoshi Nishiguchi

Active Record Relation - new vs build

These are the same as of this writing. build is an alias of new. (See: rails/activerecord/lib/active_record/relation.rb)

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”