Rails 4 Не удалось найти связь has_many, через: connection error
Right. Это просто отказывается работать. Это было часами.
модель альбома
class Album < ActiveRecord::Base
has_many :features, through: :join_table1
end
модель возможностей
class Feature < ActiveRecord::Base
has_many :albums, through: :join_table1
end
модель join_table1
class JoinTable1 < ActiveRecord::Base
belongs_to :features
belongs_to :albums
end
схема join_table1
album_id | feature_id
схема альбомов
id | title | release_date | genre | artist_id | created_at | updated_at | price | image_path
схема функций
id | feature | created_at | updated_at
После сгребания тестовой базы данных и выполнения этого теста интеграции:
require 'test_helper'
class DataFlowTest < ActionDispatch::IntegrationTest
test "create new user" do
album = albums(:one)
feature = features(:one)
album.features
end
end
Я получаю
ActiveRecord:: HasManyThroughAssociationNotFoundError: Не удалось найти ассоциацию: join_table1 в альбоме модели
Почему это?
Ответы
Ответ 1
Вам нужно добавить has_many :album_features
как к альбомам, так и к функциям (учитывая, что вы переименуете модель JoinTable1 в более значимую AlbumFeature, а соответствующая таблица будет album_features
), поскольку :through
ссылается на ассоциацию - ваша ошибка в точности соответствует он.
Или вы можете использовать has_and_belongs_to_many
, поэтому нет необходимости определять специальную модель ссылок. Но в этом случае вы должны назвать свою таблицу albums_features
.
Ответ 2
Просто определите модели следующим образом
модель альбома
class Album < ActiveRecord::Base
has_many :features, through: :join_table1
has_many :join_table1
end
модель возможностей
class Feature < ActiveRecord::Base
has_many :albums, through: :join_table1
has_many :join_table1
end
модель join_table1
class JoinTable1 < ActiveRecord::Base
belongs_to :features
belongs_to :albums
end
Ответ 3
случилось со мной.
заставил его работать, добавив таблицу соединений как has_many для обеих моделей.
как это:
модель подключения:
module Alerts
class AlertIncidentConnection < ActiveRecord::Base
belongs_to :incident
belongs_to :alert
end
end
модель оповещения:
module Alerts
class Alert < ActiveRecord::Base
has_many :alert_incident_connections, class_name: 'Alerts::AlertIncidentConnection'
has_many :incidents, through: :alert_incident_connections,class_name: 'Alerts::Incident', dependent: :destroy
end
end
модель инцидента:
module Alerts
class Incident < ActiveRecord::Base
has_many :alert_incident_connections, class_name: 'Alerts::AlertIncidentConnection'
has_many :alerts, through: :alert_incident_connections,class_name: 'Alerts::Alert' ,dependent: :destroy
end
end
файл миграции:
class CreateTableAlertIncidentConnections < ActiveRecord::Migration
def change
create_table :alert_incident_connections do |t|
t.references :alert, null: false, index: true
t.references :incident, null: false, index: true
t.timestamps
end
end
end
использование:
alert.incidents << incident
alert.save!
Ответ 4
Аналогично, как и @mad_raz, но для таблицы join необходимо иметь особые значения для belongs_to, например:
class JoinTable1 < ActiveRecord::Base
belongs_to :feature
belongs_to :album
end
Полный учебник об ассоциациях https://kolosek.com/rails-join-table/