This time, I will introduce the sample code to create pagination for the array and display it in the view.
I wrote a code like this on the controller to display my favorite products on the user's My Page. Actually, this can be done more easily by associating, so please refer to the following article! https://qiita.com/yummy888/items/22db2f8b79b5be148b69
def index
items = []
likes = Like.where(user_id: params[:item_id])
if likes.present?
likes.each { |like| items << Item.find(like.item_id)}
end
@items = Kaminari.paginate_array(items).page(params[:page]).per(15)
end
Why are you passing params [: item_id] to user_id? You may have thought, but since likes are nested in items in root.rb, this is how to pass parameters. (In the parameter, current_user is passed by path where it is: item_id) If it is true, you can nest items in uses and then nest likes to pass more beautiful parameters.
I'm doing it with haml. If it is erb, it feels like pagination is placed just below the end of each statement.
- @items.each do |item|
= link_to item_path(item), class: "user__liked__items" do
.user__liked__items__image
= image_tag "#{item.images[0].image.url}", height:"50px", width: "50px", class: "user__liked__item__image"
-if item.buyer_id.present?
.items__image__sold
.items__image__sold__inner
SOLD
.user__liked__item__details
.user__liked__item__name
= item.name
.user__liked__item__price
%span
¥
= item.price.to_s(:delimited)
%i.fas.fa-chevron-right
= paginate @items
When I can implement various things by myself, I feel that I have abandoned the search for an easier implementation method, so I would like to improve that ... Kanno: santa:
But if you want to create pagination, do you have to do various things with the controller anyway? ?? You can't do params [: page] in the view, right? Perhaps
Would you like to try a different implementation method the next time you implement this feature: frowning2:
https://blog.konboi.com/post/2013/03/31/224939/
Recommended Posts