我是 Rails 的新手,目前正在研究一个标记系统,我可以在其中为事件分配多个标签,为多个事件分配相同的标签。
标记模型如下所示:
has_many :taggings,
has_many :events, through: :taggings
事件模型如下所示:
belongs_to :user
has_many :taggings
has_many :tags, through: :taggings
我有三个这样的表:
TAGS
id | name (string)
EVENTS
id | name (string)
TAGGINGS
id | tag_id | event_id
现在我正在尝试获取前 10 个最常用的标签。我基本上需要将标记和标记表连接在一起,并在标记中按tag_id分组。像这样:
Tagging.group('tag_id').order('count_id DESC').limit(10).count('id')
但是,通过标签上的连接,以便我可以获取名称字段。
试试这个:
Tag.select('tags.*, COUNT(taggings.id) AS tagging_count').
joins(:taggings).group('tags.id').
order('tagging_count DESC').
limit(10).pluck(:name)