Skip to content

Instantly share code, notes, and snippets.

@matedemorphy
Last active June 21, 2020 04:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matedemorphy/b714b50596ca1c71f2ae5c3015d2e350 to your computer and use it in GitHub Desktop.
Save matedemorphy/b714b50596ca1c71f2ae5c3015d2e350 to your computer and use it in GitHub Desktop.
stimulus reflex - active storage
#views/categories/_category.html.slim
tr
td = category.name
td
= belonging_products(category.products)
/views/shared/_paginator_nav.html.slim
nav
ul.pagination
li.page-item
a.page-link data-page="#{pagy.prev}" data-reflex="click->TabularReflex#paginate" href="#" ←
- pagy.series.each do |item|
- if item == :gap
li.page-item.disabled
a.page-link ...
- else
li class=("page-item #{"active" if item.is_a?(String)}")
a.page-link data-page=item data-reflex="click->TabularReflex#paginate" href="#" = item
li.page-item
a.page-link data-page="#{pagy.next}" data-reflex="click->TabularReflex#paginate" href="#" →
def belonging_products(resource, empty="No products here yet", limit=5)
images = ""
content_tag :ul, class: 'list-inline' do
if(resource.empty?)
content_tag :li, class: 'list-inline-item' do
text_or_emoji(nil, 100)
end
else
resource.each do |rsc|
images += content_tag :li, class: 'list-inline-item' do
image_tag rsc.main_image, class: "table-avatar", alt: "#{rsc.name}"
end
end
return images.html_safe
end
end
#controllers/categories/categories_controller.rb
def index
@page = (session[:page] || 1).to_i
categories = Category.includes(:products_with_main_image)
pages = (categories.count / Pagy::VARS[:items].to_f).ceil
@page = 1 if @page > pages
@pagy, @categories = pagy(categories, page: @page)
end
#models/category.rb
class Category < ApplicationRecord
has_many :products
has_many :products_with_main_image, -> { with_eager_loaded_images }, class_name: "Product", foreign_key: :category_id
end
#views/categories/index.html.slim
- if @pagy.count > 0
table
thead
tr
th
| Name
th
| Products
tbody
= render @categories, cached: true
== render 'shared/paginator_nav', pagy: @pagy if @pagy.pages > 1
- else
h4 No categories yet
#models/product.rb
class Product < ApplicationRecord
belongs_to :category
has_many_attached :images
scope :with_eager_loaded_images, -> { eager_load(images_attachments: :blob) }
def main_image
images_attachments.first
end
end
class TabularReflex < ApplicationReflex
def paginate
session[:page] = element.dataset[:page].to_i
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment