13

初めてのポスター。Ransack gem とページネーションに Kaminari を使用して、ユーザーのテーブルを並べ替えようとしています。名前、ID などを使用すると並べ替えは機能しますが、posts_count との関連付けを試みると、並べ替えが壊れて機能しません。注: ビューでは、「u.posts.count」は正しく機能します。ユーザー モデルでカスタム スコープを試し、検索パラメーター用のカスタム オブジェクトを作成しましたが、何も機能していないようです。デフォルトのスコープまたは @search オブジェクトにデータがないことに問題があると思います。助けが必要!

関連するスニペットを次に示します。

models/user.rb

  has_many :posts, :dependent => :destroy 

models/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 %>
4

2 に答える 2

5

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その後、他の属性と同じように扱うことができます。

于 2012-08-23T07:55:15.390 に答える