Ask A Question

Notifications

You’re not receiving notifications from this thread.

Articles has_many tags and tags has_many articles - best way to get tag names uniq

Nikodem Gorak asked in Rails

Hi!
I have few models:
Article, Tag, ArticlesTag

class Article < ApplicationRecord  
  has_many :articles_tags
  has_many :tags, through: :articles_tags
end
​
class Tag < ApplicationRecord
  has_many :articles_tags
  has_many :articles, through: :articles_tags
end
​
class ArticlesTag < ApplicationRecord
  belongs_to :article
  belongs_to :tag
end

In Articles index view I need to get all articles tags but they should be unique. What is the best way to get them?
Tag - model at the moment is associated only with Article but in the feature it will be with other model as well.
So I can get ArticlesTag.all - this give me all tags in articles and group them by tag name to be unique.
Like this:

 ArticlesTag.all.group_by(&:tag_id)

Or even ids of tags

 ArticlesTag.all.group_by(&:tag_id).keys

That give me ids of the tag so to get names need to pull it from tag model in the loop.

tags =  ArticlesTag.all.group_by(&:tag_id).keys
tags.each do |key|
 puts Tag.find(key).name
end

Is there a better - easier way to get tags names ?

Reply

Hi there Nikodem,

First, a tiny nitpick with your naming—what you're calling ArticlesTag, I would rename to ArticleTag. It's just one tag for one article.

Now, to get all the tag names that've been assigned to at least one article, you can do something like:

Tag.joins(:article_tag).distinct.pluck(:name)
Reply
Join the discussion
Create an account Log in

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

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

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