Field::HasAndBelongsToMany

The HasAndBelongsToMany field wraps a has_and_belongs_to_many association on your model. By default it adds a list of associated records to the show page and on edit and new pages it renders a checkbox list of available records.

HasAndBelongsToMany field showing a checkbox list on an edit page

How to add a HasAndBelongsToMany field

To add the basic HasAndBelongsToMany field to a repository, return it as part of the #fields method:

def fields
  [
    Field::HasAndBelongsToMany.new(:tags)
  ]
end

Not searchable by default. The field isn’t backed by a real column, so enabling it needs a searchable lambda - see Search for columns in an associated table.

#collection_query

The chainable #collection_query method lets you control what records are available to pick from. It accepts a proc, which receives an ActiveRecord::Relation with all records for the associated repository.

Field::HasAndBelongsToMany.new(:tags)
  .collection_query(-> (query:) {
    query.some_scope
  })

The proc can accept the following keyword arguments:

  1. context: The Uchi::Context we’re currently processing.
  2. query: The ActiveRecord::Relation described above.

How to limit what records are returned

You can use #collection_query to limit what records are returned. The currently logged-in user is available as context.user, see Current user.

Field::HasAndBelongsToMany.new(:tags)
  .collection_query(-> (context:, query:) {
    query.where(id: context.user.tags)
  })

Show page

Associated records are listed in a scoped index table below the record’s other fields.

HasAndBelongsToMany field showing an associated list of tags on a show page

How to change titles in the checkbox list

The checkbox list and show page display the title of each associated record. For example, a Tag repository may use the name attribute as its title. To customize the title for a record, implement Repository#title, see repositories documentation for details.