views:

20

answers:

2

Until now, I've been using acts_as_taggable_on plugin for tagging announcements.

That plugin creates the following tables:

taggings: relates tags and announcements table(for the tagged item, it has a field called taggable_id, which I rename to "announcement_id" for what I'll explain below).

tags: has the tag ids and names.

The other day, I discovered that I had no way of getting the announcements tagged with a certain tag, but doing Announcement.tagged_with(tag_name), and I don't want to search by name, but for id.

So, as I'm using almost nothing of the functionality in that plugin, I decided to create the models for taggings and tags tables, to accomplish this: Announcement.tags.

The models' relationships look as following:

EDIT:

class Tagging < ActiveRecord::Base
  belongs_to :announcement
  belongs_to :tag
end

class Tag < ActiveRecord::Base
  has_many :taggings
  has_many :announcements, :through => :taggings
end

class Announcement < ActiveRecord::Base
  has_many :taggings
  has_many :tags, :through => :taggings

Why can't I execute the command Announcement.tags? Because when I try, I get

undefined method `tags'

+1  A: 

What you've actually posted is that you've tried Announcement.tags. But tags would be a method on an Announcement instance, and that's calling it as a method on the Announcement class, which won't work.

Assuming you're actually calling an_announce.tags, you also need Announcement and Tag to have many taggings - like so:

class Announcement < ActiveRecord::Base
  has_many :taggings
  has_many :tags, :through => :taggings
end

class Tag < ActiveRecord::Base
  has_many :taggings
  has_many :announcements, :through => :taggings
end
Chris
+1  A: 

you should try @announcement.tags, since tags is an instance method of Announcement class(model).

@announcement = Announcement.first
Vamsi
So, what if I wanted to get all the announcements tagged with a certain tag_id?
Brian Roisentul
`Tag.find(tag_id).announcements`
Chris
That doesn't work.
Brian Roisentul
In what way doesn't it work? You'll also need `Tag` to `has_many :taggings` - which I'll add to my answer.
Chris
I've edited my post with the updated code. It does not work when I do Tag.find(tag_id).announcements. It tells me "undefined method announcements" for that tag.
Brian Roisentul
It works now! I deleted the plugin, and it seems to be working now. Thank you!
Brian Roisentul