Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.