Problem building relationships between models

Posted by Brian Roisentul on Stack Overflow See other posts from Stack Overflow or by Brian Roisentul
Published on 2010-06-16T14:52:25Z Indexed on 2010/06/16 15:02 UTC
Read the original article Hit count: 136

Filed under:

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:

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

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

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

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

undefined method `tags'

© Stack Overflow or respective owner

Related posts about ruby-on-rails