Right. This simply refuses to work. Been at this for hours.
album model
class Album < ActiveRecord::Base
has_many :features, through: :join_table1
end
features model
class Feature < ActiveRecord::Base
has_many :albums, through: :join_table1
end
join_table1 model
class JoinTable1 < ActiveRecord::Base
belongs_to :features
belongs_to :albums
end
join_table1 schema
album_id | feature_id
albums schema
id | title | release_date | genre | artist_id | created_at | updated_at | price | image_path
features schema
id | feature | created_at | updated_at
Upon raking the test database, and running this integration test:
require 'test_helper'
class DataFlowTest < ActionDispatch::IntegrationTest
test "create new user" do
album = albums(:one)
feature = features(:one)
album.features
end
end
I get
ActiveRecord::HasManyThroughAssociationNotFoundError: Could not find the association :join_table1 in model Album
Why is this?
You need to add has_many :album_features
both to Album and Feature models (given that you rename JoinTable1 model to more meaningful AlbumFeature, and corresponding table would be album_features
), as :through
references association - your error is exactly about it.
Or you can use has_and_belongs_to_many
so there will be no need to define special link model. But in that case you must name your table albums_features
.
Just define the models as follow
album model
class Album < ActiveRecord::Base
has_many :join_table1
has_many :features, through: :join_table1
end
features model
class Feature < ActiveRecord::Base
has_many :join_table1
has_many :albums, through: :join_table1
end
join_table1 model
class JoinTable1 < ActiveRecord::Base
belongs_to :features
belongs_to :albums
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With