O.Vykhor
O.Vykhor

Reputation: 479

searchkick requests together with active record requests rails

I have a trouble. For example I have a model Article, and my search_data method below

def search_data
  title: title,
  body: body
end

And I need to receive some records from my controller according to some attributes, for example:

def index
  @articles = Article.where(user_id: user_id).search(query)
end

But this approach received all data whos according to query in search method ignoring where method, while I need to search by search method among data received by where method. How to resolve this?

Update

Desirely to use where before search method, not the inside it

Upvotes: 1

Views: 1274

Answers (2)

Rene Chan
Rene Chan

Reputation: 985

The key here tis to make sure that every attribute in your where query also exist in your search_data method. Example:

Message.search search_term, where: {or: [[{user_id: current_user.id}, {recipient_id: current_user.id}]]}

I am looking to find messages with the search_term where the current user is either sender or recipient.

Therefore in my search_data method (in model.rb) I should have:

  def search_data
    {   user_id: user_id,
        recipient_id: recipient_id,
        title: title,
        description: description,
    }

And this works well. this is using Searchkick gem.

Upvotes: 0

tombeynon
tombeynon

Reputation: 2356

It appears SearchKick doesn't allow you to chain a search onto an ActiveRecord Relation like that. It uses ElasticSearch to search instead of your database so if you did that you would be querying two databases for the information. However, it does provide a where option for the search method:

Article.search(query, where: {user_id: user_id})

If you absolutely have to make the ActiveRecord query first, you could get the IDs from the first query and provide them to the second.

ids = Article.where(user_id: user_id)
Article.search(query, where: {id: ids})

Upvotes: 1

Related Questions