Search code examples
ruby-on-railscontrollerransack

Ransack custom default sort


After spending the second half of my day on this hopefully just in need of some fresh eyes. Getting this error while trying to set a default sort for my index controller using ransack and I'm not sure why

undefined method `split' for #<Post:0x007fabedac69a8>

Here is my controller

class PostsController < ApplicationController
  def index
    @search = Post.search(params[:q])
    @search.sorts = Post.find_with_reputation(:votes,:all, order: "votes desc") if @search.sorts.empty?
    @posts = @search.results
  end
end

Using active record reputation and want the default load to sort by highest votes as you can see. Maybe there is a better way to achieve have the page load with sorted votes and allow ransack searching? Thoroughly confused at the moment.


Solution

  • Instead of @search.sort try to assign it into another variable. Also instead of results use result

    class PostsController < ApplicationController
      def index
        @search = Post.search(params[:q])
        @search_r = Post.find_with_reputation(:votes,:all, order: "votes desc") if @search.sorts.empty?
        @posts = @search_r.result
      end
    end