Ask A Question


You’re not receiving notifications from this thread.

acts-as-taggable-on cause SQL errors when ordered by relation

Drew Bragg asked in Gems / Libraries

I’m having a weird issue with acts-as-taggable-on when using tagged_with and the any flag.

My model looks something like this:

class Document < ApplicationRecord
  belongs_to :phase, optional: true

  scope :search_by_drug, ->(drug) { tagged_with(drug, on: :drug) if drug.present? }
  scope :search_by_area, ->(area) { tagged_with(area, on: :area) if area.present? }
  scope :search_by_type, ->(types) { tagged_with(types, on: :doc_type, any: true) if types.present? }
  scope :search_by_tags, ->(tags) { tagged_with(tags, on: :tags, any: true) if tags.present? }

  acts_as_taggable_on :tags, :drug, :area, :doc_type


and in my controller this is where I'm querying:

class DocumentsController < ApplicationController
  include Pagy::Backend

  # GET /documents
  def index
    @pagy, @documents = pagy(
      Document.includes(:phase, :taggings)
      items: 5



  def sort_by
    return @sort_by = '' if params[:sort] == 'phase'

    @sort_by = params[:sort] || 'date'

  def order
    @order = params[:order] || 'asc'

  def sort_order
    "#{sort_by} #{order}"


When I'm seaching with taggs or by types and I try to order the phase column I’m thrown an error that looks like this:

ERROR: for SELECT DISTINCT, ORDER BY expressions must appear in select list
LINE 1: ...) AND "taggings"."context" = 'doc_type') ORDER BY phases.nam...

I’ve done a bunch of searching but the closest issues I could come up with was an old issue on the acts-as-taggable-on github but it was closed because (according to them) they had merged a PR that fixed the issue and there’s nothing new in their issues or SO.

Can anyone point me in the right direction?

Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 83,770+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.