Home > Enterprise >  Rails has_many :through polymorphic relationship not working
Rails has_many :through polymorphic relationship not working

Time:04-06

I have the following three models:

Event:

class Event < ApplicationRecord
  has_many :taggings, as: :taggable, dependent: :destroy
  has_many :tags, through: :taggings
end

events table:

Column   |  Type    |                     Modifiers
--------- ---------- ----------------------------------------------------
id       | bigint   | not null
title | string | not null
content | text | not null

Tag:

class Tag < ApplicationRecord
  has_many :taggings, dependent: :destory
  has_many :events, through: :taggings, source: :taggable, source_type: 'Event'
end

tags table:

Column   |  Type    |                     Modifiers
--------- ---------- ----------------------------------------------------
id       | bigint   | not null
name | string | not null

Tagging:

class Tagging < ApplicationRecord
  belongs_to :taggable, polymorphic: true
  belongs_to :tags
end

taggings table:

Column   |  Type    |                     Modifiers
--------- ---------- ----------------------------------------------------
id       | bigint   | not null
taggable_id | integer | not null
taggable_type | string | not null
tag_id | integer | not null | FK_INDEX

Now the problem is I can't seem to use any of these relationships and getting errors indicating no associations exist.

event = Event.find(x)
event.tags

Error: 
NameError: uninitialized constant Event::Tags

event.taggable

Error:
NoMethodError: undefined method `taggable' for #<Event>

I can't figure out if my associations are setup right or my use case is wrong?

How would I add an assocation through the mode? How would I query tags through Event model?

CodePudding user response:

Its a simple pluralization error:

class Tagging < ApplicationRecord
  belongs_to :taggable, polymorphic: true
  belongs_to :tag
end

The names of belongs_to and has_one associations should always be singular.

If you look at the error message NameError: uninitialized constant Event::Tags you can see that its looking for Tags and not Tag.

  • Related