feat: Sort articles based on views (#7599)

This commit is contained in:
Pranav Raj S
2023-07-24 20:27:43 -07:00
committed by GitHub
parent 703e19304d
commit a6a0e78bbe
6 changed files with 34 additions and 13 deletions

View File

@@ -8,13 +8,22 @@ class Public::Api::V1::Portals::ArticlesController < Public::Api::V1::Portals::B
def index
@articles = @portal.articles
@articles = @articles.search(list_params) if list_params.present?
@articles.order(position: :asc)
order_by_sort_param
@articles.page(list_params[:page]) if list_params[:page].present?
end
def show; end
private
def order_by_sort_param
@articles = if list_params[:sort].present? && list_params[:sort] == 'views'
@articles.order_by_views
else
@articles.order_by_position
end
end
def set_article
@article = @portal.articles.find_by(slug: permitted_params[:article_slug])
@article.increment_view_count
@@ -35,7 +44,7 @@ class Public::Api::V1::Portals::ArticlesController < Public::Api::V1::Portals::B
end
def list_params
params.permit(:query, :locale)
params.permit(:query, :locale, :sort)
end
def permitted_params

View File

@@ -65,6 +65,7 @@ class Article < ApplicationRecord
scope :search_by_status, ->(status) { where(status: status) if status.present? }
scope :order_by_updated_at, -> { reorder(updated_at: :desc) }
scope :order_by_position, -> { reorder(position: :asc) }
scope :order_by_views, -> { reorder(views: :desc) }
# TODO: if text search slows down https://www.postgresql.org/docs/current/textsearch-features.html#TEXTSEARCH-UPDATE-TRIGGERS
pg_search_scope(

View File

@@ -10,6 +10,6 @@ json.views article.views
if article.author.present?
json.author do
json.partial! 'public/api/v1/models/portal/author', formats: [:json], resource: article.author
json.partial! 'public/api/v1/models/hc/author', formats: [:json], resource: article.author
end
end

View File

@@ -1 +1 @@
json.array! @portals, partial: 'public/api/v1/models/portal', formats: [:json], as: :portal
json.array! @portals, partial: 'public/api/v1/models/hc/portal', formats: [:json], as: :portal

View File

@@ -1 +1 @@
json.partial! 'public/api/v1/models/portal', formats: [:json], portal: @portal
json.partial! 'public/api/v1/models/hc/portal', formats: [:json], portal: @portal