Я пытаюсь понять обратные полиморфные ассоциации в Rails. Я следовал this guide, но у меня есть ошибка. Когда я пишу some_type_object.clubs
он работает довольно хорошо, но когда я пытаюсь some_club_object.type
я получаю сообщение об ошибке:Рельсы. Обратные полиморфные ассоциации
ActiveRecord::HasManyThroughAssociationNotFoundError: Could not find the association :type_elements in model Club
Как это исправить?
Вот мои модели:
class Club < ActiveRecord::Base
has_one :type_element, as: :element
has_one :type, through: :type_elements
end
class Event < ActiveRecord::Base
has_one :type_element, as: :element
has_one :type, through: :type_elements
end
class Type < ActiveRecord::Base
has_many :type_elements
has_many :clubs, through: :type_elements, source: :element, source_type: 'Club'
has_many :events, through: :type_elements, source: :element, source_type: 'Event'
end
class TypeElement < ActiveRecord::Base
belongs_to :type
belongs_to :element, polymorphic: true
end
Мои Миграции:
class CreateClubs < ActiveRecord::Migration
def change
create_table :clubs do |t|
t.string :name
t.belongs_to :type
t.timestamps null: false
end
end
end
class CreateEvents < ActiveRecord::Migration
def change
create_table :events do |t|
t.string :name
t.belongs_to :type
t.timestamps null: false
end
end
end
class CreateTypeElements < ActiveRecord::Migration
def change
create_table :type_elements do |t|
t.belongs_to :type, index: true
t.integer :element_id
t.string :element_type
t.timestamps null: false
end
add_foreign_key :type_elements, :types
add_foreign_key :type_elements, :elements
end
end
class CreateTypes < ActiveRecord::Migration
def change
create_table :types do |t|
t.string :name
t.timestamps null: false
end
end
end
Большое спасибо, это помогло. – skowl