与Ransack的Rails排序关联 [英] Rails sorting associations with Ransack

查看:162
本文介绍了与Ransack的Rails排序关联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

第一次海报.我正在尝试使用Ransack gem和Kaminari进行分页的用户列表.当我使用名称,id等进行排序时,但是当我尝试与posts_count关联时,排序会中断,并且将无法工作.注意:在视图中,'u.posts.count'正常工作.我在用户模型中尝试了自定义范围,并为搜索参数创建了自定义对象,但似乎没有任何效果.我想我在默认范围或@search对象没有数据时遇到了麻烦.需要帮助!

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 association with posts_count, sorting breaks and won't work. Note: in the view, 'u.posts.count' work correctly. I have tried custom scopes in the users model, and creating custom objects for the search params but nothing seems to work. I think I am having trouble either in the default scope or the @search object not having the data. Need help!

以下是一些相关的摘要:

Here are some relevant snippets:

models/user.rb

  has_many :posts, :dependent => :destroy 

models/post.rb

  belongs_to :user 

  default_scope :order => 'post.created_at DESC'

controllers/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

视图/用户/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模型中:

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

并像这样使用它:

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

然后,您可以像对待其他任何属性一样对待posts_count.

then, you can treat posts_count like any other attribute.

这篇关于与Ransack的Rails排序关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆