Skip to content

Commit

Permalink
Merge pull request #197 from avo-hq/searching-with-associations
Browse files Browse the repository at this point in the history
  • Loading branch information
adrianthedev authored Apr 18, 2024
2 parents 79120ba + 9550f28 commit 11d38e3
Showing 1 changed file with 48 additions and 0 deletions.
48 changes: 48 additions & 0 deletions docs/3.0/search.md
Original file line number Diff line number Diff line change
Expand Up @@ -252,3 +252,51 @@ class Avo::Resources::Order < Avo::BaseResource
}
end
```

## Searching within associations

In some cases, you might need to search for records based on attributes of associated models. This can be achieved by adding a few things to the search query. Here's an example of how to do that:

Assuming you have two models, `Application` and `Client`, with the following associations:

```ruby
class Application < ApplicationRecord
belongs_to :client
end

class Client < ApplicationRecord
has_many :applications
end
```

You can perform a search on `Application` records based on attributes of the associated `Client`. For example, searching by the client's email, name, or phone number:

```ruby{5,10-14}
class Application < ApplicationRecord
self.search = {
query: lambda {
query
.joins(:client)
.ransack(
id_eq: params[:q],
name_cont: params[:q],
workflow_name_cont: params[:q],
client_id_eq: params[:q],
client_first_name_cont: params[:q],
client_last_name_cont: params[:q],
client_email_cont: params[:q],
client_phone_number_cont: params[:q],
m: 'or'
).result(distinct: false)
},
item: lambda {
{
title: record.external_client_id,
description: "#{record.client.name}, #{record.client.email}"
}
}
}
end
In the above example, ransack is used to search for `Application` records based on various attributes of the associated `Client`, such as client_email_cont and client_phone_number_cont. The joins method is used to join the applications table with the clients table to perform the search efficiently.
This approach allows for flexible searching within associations, enabling you to find records based on related model attributes.

0 comments on commit 11d38e3

Please sign in to comment.