0
0

More than 3 years have passed since last update.

Kaminariで、controllerでメソッドチェインできない時

Posted at

Kaminariで、メソッドチェインができない...

Kaminariを使って無限スクロールを実装していたところ、

controller.rb
  def index
    # コイツは普通に取得できるけど
      @posts = current_user.posts.where(created_at: Date.today).page(params[:page]).per(8)

    # sort_by, sort_by!, reverse!でつなげた時はエラーになる
      @posts = current_user.posts.where(created_at: Date.today).sort_by {|f| f[:updated_at]}.reverse!.page(params[:page]).per(8)
  end

解決策

上は、メソッドチェインで取得したのはインスタンスオブジェクトなのに対し、
下は、sortメソッドなどは、Enumerable#sortというRuby標準のメソッドで配列を返す。

そもそも

Kaminariのpageは、配列に対して使えなかったらしい。知らなかった。

もともと、kaminari が扱う page は scope だったかと思います。なので、配列(Array)に対しては使えませんでした。
http://hamasyou.com/blog/2011/06/14/kaminari-paginate-array/

そして、あらかじめKaminariに用意されているpaginate_arrayというメソッドがあることを発見。
引数に配列を渡せばオブジェクトに変換してくれる。

1. インスタンスオブジェクトに配列を格納 2.paginate_arrayの引数に渡す

controller.rb
  def index
      @posts = current_user.posts.where(created_at: Date.today).sort_by {|f| f[:updated_at]}.reverse!

      # paginate_arrayの引数に、格納した配列を渡す。
      @posts = Kaminari.paginate_array(@posts).page(params[:page]).per(8)
  end

カミナリについて少し詳しくなれました。(ホッ

こちらの記事を参考
https://stackoverflow.com/questions/16326855/rails-kaminari-how-to-order-a-paginated-array
https://teratail.com/questions/226802

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0