ruby-on-railsactiverecordransackrails-bullet

How to avoid N+1 queries with Ransack


I've beeen using Ransack in one of my projects and also using Bullet to spot some N+1 queries in my controllers. However, I'm not quite sure how to accomplish that while using Ransack. There are two models involved, Patch and Image. And a Patch has_one Image. The action code is the follow:

  def index
    @q = Patch.search(params[:q])
    @patches = @q.result(distinct: true).order("code DESC").paginate(:page => params[:page], :per_page => 10)
  end

Any thoughts?


Solution

  • This is working to me in a project. def index @q = Client.includes(zone: :user).ransack(params[:q]) @clients = @q.result.page(params[:page]).decorate end

    In your case should be

    def index
        @q = Patch.includes(:image).search(params[:q])
        @patches = @q.result(distinct: true).order("code DESC").paginate(:page => params[:page], :per_page => 10)
    end