6
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Rails】Kaminariで同一ページにもっと見るを複数実装する

Posted at

通常の場合

home_controller.rb
def index
  @cats = Cat.page(params[:page]).per(1)
end
app/views/home/index.html.erb
<%= paginate @cats %>

複数の場合

home_controller.rb
def index
  @cats = Cat.page(params[:cats_page]).per(1)
  @dogs = Dog.page(params[:dogs_page]).per(1)
end
app/views/home/index.html.erb
<%= paginate @cats, param_name: 'cats_page' %>
<%= paginate @dogs, param_name: 'dogs_page' %>

ajaxを利用したもっと見るの場合

home_controller.rb
def index
  @cats = Cat.page(params[:page]).per(1)
  @dogs = Dog.page(params[:page]).per(1)
  return unless request.xhr?
  case params[:type]
  when 'dog', 'cat'
    render "#{params[:type]}"
  end
end
app/views/home/index.html.erb
<%= link_to_next_page @cats, 'もっと見る', remote: true, params: { type: :cat }, id: 'more-cat' %>
<%= link_to_next_page @dogs, 'もっと見る', remote: true, params: { type: :dog }, id: 'more-dog' %>
app/views/home/cat.js.erb
$('.cat-wrap').append('<%= escape_javascript(render 'cat', object: @cats) %>');
$('#more-cat').replaceWith('<%= escape_javascript(link_to_next_page(@cats, 'もっと見る', params: { type: :cat }, remote: true, id: 'more-cat')) %>');

app/views/home/dog.js.erb
$('.dog-wrap').append('<%= escape_javascript(render 'dog', object: @dogs) %>');
$('#more-dog').replaceWith('<%= escape_javascript(link_to_next_page(@dogs, 'もっと見る', params: { type: :dog }, remote: true, id: 'more-dog')) %>');

参考

https://qiita.com/Coolucky/items/bde74b020b8d37ccf426
https://www.rubydoc.info/github/amatsuda/kaminari/Kaminari/ActionViewExtension

6
3
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
6
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?