Rails排序与Ransack的关联

Sea*_*mas 12 sorting ruby-on-rails-3 ransack

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

以下是一些相关的片段:

车型/ user.rb

  has_many :posts, :dependent => :destroy 
Run Code Online (Sandbox Code Playgroud)

车型/ post.rb

  belongs_to :user 

  default_scope :order => 'post.created_at DESC'
Run Code Online (Sandbox Code Playgroud)

控制器/ 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
Run Code Online (Sandbox Code Playgroud)

意见/用户/ 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 %>
Run Code Online (Sandbox Code Playgroud)

Mau*_*uan 5

您可以向User模型添加范围:

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

并像这样使用它:

@search = User.with_posts.search(params[:q]) # Ransack
Run Code Online (Sandbox Code Playgroud)

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