У меня есть следующие три модели:
Мероприятие:
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
Ярлык:
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
Пометка:
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
Теперь проблема в том, что я не могу использовать какие-либо из этих отношений и получаю ошибки, указывающие на отсутствие ассоциаций.
event = Event.find(x)
event.tags
Error:
NameError: uninitialized constant Event::Tags
event.taggable
Error:
NoMethodError: undefined method `taggable' for #<Event>
Я не могу понять, правильно ли настроены мои ассоциации или мой вариант использования неверен?
Как добавить ассоциацию через режим? Как мне запрашивать теги через модель событий?
@mrrogers, ты прав, но немного осторожен. Название ассоциаций belongs_to
и has_one
должно быть в единственном числе.
Это простая ошибка множественного числа:
class Tagging < ApplicationRecord
belongs_to :taggable, polymorphic: true
belongs_to :tag
end
Имена ассоциаций belongs_to
и has_one
должны быть в единственном числе.
Если вы посмотрите на сообщение об ошибке NameError: uninitialized constant Event::Tags
, вы увидите, что он ищет Tags
, а не Tag
.
Я думаю, что в
Tagging
вам может понадобитьсяbelongs_to :tag
(единственное число)