首次发布海报。我正在尝试对使用Ransack-gem和Kaminari进行分页的用户表进行排序。当我使用name、id等时,排序是有效的,但当我尝试与posts_count关联时,排序会中断并且不起作用。注意:在视图中,"u.posts.count"工作正常。我尝试过在用户模型中自定义作用域,并为搜索参数创建自定义对象,但似乎什么都不起作用。我想我在默认范围或@search对象没有数据时遇到了问题。需要帮助!
以下是一些相关的片段:
型号/用户.rb
has_many :posts, :dependent => :destroy
型号/post.rb
belongs_to :user
default_scope :order => 'post.created_at DESC'
控制器/users_controller.rb
def index
@title = "User Index"
@search = User.search(params[:q]) # Ransack
@total_users = User.all.count
# .per(10) is the per page for pagination (Kaminari).
@users = @search.result.order("updated_at DESC").page(params[:page]).per(10) #This displays the users that are in the search criteria, paginated.
end
views/users/index.html.erb
..
<%= sort_link @search, :posts_count, "No. of Posts" %> #Sort links at column headers
..
<% @users.each do |u| %> #Display everything in the table
<%= u.posts.count %>
<% end %>
您可以为User
模型添加一个作用域:
def self.with_posts
joins(:posts).group('posts.id').select('users.*, count(posts.id) as posts_count')
end
并像这样使用:
@search = User.with_posts.search(params[:q]) # Ransack
然后,可以像对待任何其他属性一样对待posts_count
。
我找到了一个解决方案:
控制器:
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
视图:
<th><%= sort_link @search, :count, "posts count" %></th>