ruby on rails - Sort by count of associated has_many model -
got following models
class document has_many :document_tag_links has_many :document_tags, through: :document_tag_links class documenttag has_many :document_tag_links has_many :documents, through: :document_tag_links class documenttaglink belongs_to :document belongs_to :document_tag
now, i'm trying sort documenttags how many documents associated with. i've tried following:
scope :top10, -> { joins(:document_tag_links). select("documents.*, count(document_id) documents_count"). group("document_id"). order("documents_count desc") }
but gives me following error:
activerecord::statementinvalid: pg::undefinedtable: error: missing from-clause entry table "documents" line 1: select documents.*, count(document_id) as... ^ : select documents.*, count(document_id) documents_count "document_tags" inner join "document_tag_links" on "document_tag_links"."document_tag_id" = "document_tags"."id" group document_id order documents_count desc
could point me in right direction?
solution after discussion in comments.
scope :top10, -> { joins(:document_tag_links) .select("document_tags.*, count(document_id) documents_count") .group("document_tags_id") .order("documents_count desc") }
Comments
Post a Comment