Wilko
Wilko

Reputation: 5

Finding data through a habtm association

I can't wrap my head around how to accomplish this and hoping that someone will be able to help - I am sure this will be something simple!

I'm trying to implement a "tag cloud" from scratch in my rails app, (fairly similar to the episode as posted on railscasts.com) with the added complexity that I only want to show tags in my "cloud", that relate to the results that are returned. For example, let's say that in the index view, the user has filtered the results. My desire is to only show tags from the filtered result set.

I have two models that contain a HABTM association between them:

class Article < ActiveRecord::Base
has_and_belongs_to_many :tags
...
end

class Tag < ActiveRecord::Base
has_and_belongs_to_many :articles
...
end

In my Article controller, I have an @articles variable which gives me the results that show in my index action. For the purpose of this explanation, let's say it's:

@article = Article.all

What I thought I'd be able to do is to call @article.tags, hoping it would return the associated tags for all articles, within the results. I thought I'd be able to then group and iterate through them, showing them in the cloud. However, this throws an "undefined method error".

I've been playing in the rails console and found that if I run:

>> @articles = Article.find(1)
>> @articles.tags

Then all tags associated with that article are returned to me. Why can't you call that on .all?

If I was to use SQL directly I'd do something like:

SELECT name, COUNT(*)
FROM tags INNER JOIN articles_tags on ... INNER JOIN articles on...
WHERE // filtered results
GROUP BY name

I guess that's a simplified equivalent of what I'm trying to do but using the rails-query-lingo.

Any ideas?

Upvotes: 0

Views: 318

Answers (1)

mohameddiaa27
mohameddiaa27

Reputation: 3597

You can get the Tags that have Articles by:

Tag.joins(:articles)

Same applies for atricles that have tags.

Article.joins(:tags)

You may prefer using has_many through instead of habtm, that gives you more control over the join table, check this question

Upvotes: 1

Related Questions