nico_lrx
nico_lrx

Reputation: 280

Rails : includes doesn't work in model scope

I created a scope in my book model and want to include the author relation. Unfortunately, the relation isn't loaded with the following code:

scope :search, ->(title) {
    quoted_title = ActiveRecord::Base.connection.quote_string(title)
        includes(:author).where("title % :title", title: title).
      order(Arel.sql("similarity(title, '#{quoted_title}') DESC"))
  }

I tried several tweaks such as using joins(:author).merge() but the relation is still not loaded. Any idea how to load the relation within a scope? Thanks.

Here is the controller with the method I called through Ajax to render search results:

def search
   results_books = Book.search(search_params[:q]).first(5)
   results_authors = Author.search(search_params[:q]).first(5)

     results = results_books + results_authors

   render json: { results: results }, status: :ok
  end

Upvotes: 1

Views: 393

Answers (1)

a.fahmiin
a.fahmiin

Reputation: 400

For the search function in your scope, if I understand correctly, you are trying to pick out books that matches the searched params according to title field. If so, may I suggest a shorter version like this:

 scope :search, lambda { |title|
    where('title like ?', "%#{title}%")
  }

As for including the associated authors into the json output. We usually use JBuilder when returning JSON objects to the front-end. If you insist in doing it using basic RoR then check out this answer by Substanstial https://stackoverflow.com/a/26800097/9972821

This isn't tested so let me know how well it goes. The rest of the post I shared also touches on JBuilder as the preferred alternative.

Upvotes: 1

Related Questions