Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 4 Could not find the association has_many, through: relationship error

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?

like image 635
Starkers Avatar asked Sep 24 '13 10:09

Starkers


2 Answers

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.

like image 137
biomancer Avatar answered Sep 20 '22 14:09

biomancer


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
like image 21
a14m Avatar answered Sep 18 '22 14:09

a14m