Rails sorting associations with Ransack

前端 未结 2 1428
有刺的猬
有刺的猬 2020-12-31 08:21

first time poster. I am trying to sort a table of users using the Ransack gem and Kaminari for pagination. When I use name, id, etc. sorting works but when I try an associat

相关标签:
2条回答
  • 2020-12-31 08:52

    You can add a scope to your User model:

    def self.with_posts
      joins(:posts).group('posts.id').select('users.*, count(posts.id) as posts_count')
    end
    

    and use it like this:

    @search = User.with_posts.search(params[:q]) # Ransack
    

    then, you can treat posts_count like any other attribute.

    0 讨论(0)
  • 2020-12-31 08:57

    I found a solution:

    Controller:

    def index
        sql = "users.*, (select count(posts.id) from posts\
        where posts.user_id = users.id) as count"
        @search = User.select(sql).search(params[:q])
    
        if params[:q] && params[:q][:s].include?('count')
          @users = @search.result.order(params[:q][:s])
        else
          @users = @search.result
        end
        .......
    end
    

    View:

    <th><%= sort_link @search, :count, "posts count" %></th>
    
    0 讨论(0)
提交回复
热议问题