-->

导轨和洗劫排序协会(Rails sorting associations with Ransack)

2019-06-27 05:49发布

首次海报。 我想排序使用洗劫的宝石和雷的分页用户的表。 当我使用的名称,ID等排序的作品,但是当我尝试的关联与POSTS_COUNT,分拣休息和将无法正常工作。 注:在视图中,“u.posts.count”正常工作。 我试图在用户模式自定义范围,并创建自定义对象的搜索PARAMS,但似乎没有任何工作。 我觉得我有无论是在默认范围或不具有数据@search对象的麻烦。 需要帮忙!

下面是一些相关的片段:

车型/ user.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

意见/用户/ 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 %>

Answer 1:

您可以将范围添加到您的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像任何其他属性。



Answer 2:

我发现了一个解决方案:

控制器:

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>


文章来源: Rails sorting associations with Ransack