Rails 4找不到关联has_many,通过:关系错误

Sta*_*ers 14 ruby-on-rails has-many-through ruby-on-rails-4

对.这简直就是拒绝工作.在这几个小时.

专辑模型

class Album < ActiveRecord::Base
  has_many :features, through: :join_table1
end
Run Code Online (Sandbox Code Playgroud)

功能模型

class Feature < ActiveRecord::Base
  has_many :albums, through: :join_table1
end
Run Code Online (Sandbox Code Playgroud)

join_table1模型

class JoinTable1 < ActiveRecord::Base
  belongs_to :features
  belongs_to :albums
end
Run Code Online (Sandbox Code Playgroud)

join_table1架构

album_id | feature_id
Run Code Online (Sandbox Code Playgroud)

专辑架构

id | title | release_date | genre | artist_id | created_at | updated_at | price | image_path
Run Code Online (Sandbox Code Playgroud)

功能架构

id | feature | created_at | updated_at
Run Code Online (Sandbox Code Playgroud)

在调试测试数据库并运行此集成测试时:

require 'test_helper'

class DataFlowTest < ActionDispatch::IntegrationTest
  test "create new user" do
    album = albums(:one)
    feature = features(:one)
    album.features
  end
end
Run Code Online (Sandbox Code Playgroud)

我明白了

ActiveRecord :: HasManyThroughAssociationNotFoundError:在模型相册中找不到关联:join_table1

为什么是这样?

bio*_*cer 19

您需要将has_many :album_features两者都添加到Album和Feature模型(假设您将JoinTable1模型重命名为更有意义的AlbumFeature,并且相应的表将是album_features),作为:through引用关联 - 您的错误正是它的错误.

或者你可以has_and_belongs_to_many这样使用,因此不需要定义特殊的链接模型.但在这种情况下,你必须为你的桌子命名albums_features.

  • 我不认为连接表的命名约定与has_many,through关系有关. (2认同)

a14*_*14m 12

只需定义模型如下

专辑模型

class Album < ActiveRecord::Base
  has_many :join_table1
  has_many :features, through: :join_table1
end
Run Code Online (Sandbox Code Playgroud)

功能模型

class Feature < ActiveRecord::Base
  has_many :join_table1
  has_many :albums, through: :join_table1
end
Run Code Online (Sandbox Code Playgroud)

join_table1模型

class JoinTable1 < ActiveRecord::Base
  belongs_to :features
  belongs_to :albums
end
Run Code Online (Sandbox Code Playgroud)