Skip to content

WARNING

It's important to set the inverse_of as often as possible to your model's association attribute.

Has One

The HasOne association shows the unfolded view of your has_one association. It's like peaking on the Show view of that associated record. The user can also access the Attach and Detach buttons.

ruby
field :admin, as: :has_one
Has one

Options

searchable

Turns the attach field/modal from a select input to a searchable experience

ruby
class Avo::Resources::CourseLink < Avo::BaseResource
  def fields
    field :links,
      as: :has_many,
      searchable: true
  end
end

WARNING

Avo uses the search feature behind the scenes, so make sure the target resource has the search_query option configured.

ruby
# app/avo/resources/course_link.rb
class Avo::Resources::CourseLink < Avo::BaseResource
  self.search = {
    query: -> {
      query.ransack(id_eq: params[:q], link_cont: params[:q], m: "or").result(distinct: false)
    }
  }
end

Default

false

Possible values

true, false

attach_scope

Scope out the records the user sees on the Attach modal.

Default

nil

Possible values

ruby
field :user,
  as: :belongs_to,
  attach_scope: -> { query.non_admins }

Pass in a block where you attach scopes to the query object and parent object, which is the actual record where you want to assign the association. The block is executed in the ExecutionContext.

WARNING

The attach_scope will not filter the records in the listing from has_many or has_and_belongs_to_many associations. Use scope or a Pundit policy Scope for that.

ruby
field :members,
  as: :has_one,
  attach_scope: -> { query.where.not(team_id: parent.id) }

In this example, in the attach_scope, we ensure that when attaching members to a team, only those who are not already members will appear in the list of options.

Show on edit screens

By default, has_and_belongs_to_many is only visible on the Show page. If you want to enable it on the Edit page, too, you need to add the show_on: :edit option.

WARNING

Adding associations on the New screen is not currently supported. The association needs some information from the parent record that hasn't been created yet (because the user is on the New screen).

You may use the redirect helpers to have the following flow:

  1. User is on the New view. They can't see the association panels yet.
  2. User creates the record.
  3. They get redirected to the Show/Edit view, where they can see the association panels.
  4. User attaches associations.