Skip to content

Instantly share code, notes, and snippets.

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 lujanfernaud/b018d38d2ecb0d80cc59ac0cea54929e to your computer and use it in GitHub Desktop.
Save lujanfernaud/b018d38d2ecb0d80cc59ac0cea54929e to your computer and use it in GitHub Desktop.
Rails: Order by Priority and Date with Limit for Category

Rails: Order by Priority and Date with Limit for Category

# group.rb

# When we pass NULL to LIMIT, Postgres treats it as LIMIT ALL (no limit).
# https://www.postgresql.org/docs/current/static/sql-select.html#SQL-LIMIT
def topics_prioritized(normal_topics_limit: nil)
  ids = topic_ids(normal_topics_limit)

  topics.where(id: ids).prioritized
end

private

  def topic_ids(normal_topics_limit)
    special_topics_ids = special_topics.pluck(:id)
    normal_topics_ids  = normal_topics.limit(normal_topics_limit).pluck(:id)

    special_topics_ids + normal_topics_ids
  end

  def special_topics
    Topic.where(group: self).where.not(type: "Topic").prioritized
  end
# topic.rb

scope :prioritized, -> {
  order(priority: :desc, last_commented_at: :desc).includes(:user)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment