Brian Roisentul
Brian Roisentul

Reputation: 4750

Problem building relationships between models

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'

Upvotes: 0

Views: 66

Answers (2)

Chowlett
Chowlett

Reputation: 46677

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

Upvotes: 1

Vamsi
Vamsi

Reputation: 278

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

@announcement = Announcement.first

Upvotes: 1

Related Questions