LoginSignup
2
1

More than 3 years have passed since last update.

Ransackでアソシエーション先のcountでソートする場合

Posted at

以下のようなクラスがあったとする。

class Post < ApplicationRecord
  has_many :comments
end
class Comment < ApplicationRecord
  belongs_to :post
end

以下のようなransackerをPost(親側)に追記する。

    ransacker :comment_count do
      query = <<-SQL
        (SELECT
           COUNT(comments.post_id)
         FROM
           comments
         WHERE
           comments.post_id = posts.id
         GROUP BY
           comments.post_id)
      SQL
      Arel.sql(query)
    end

あとはview側で通常のソートと同じように実装する。

<th><%= sort_link(@q, :comment_count) %></th>
2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1