简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM