2013-09-24 138 views
12

没错。这只是拒绝工作。在这里呆了几个小时。Rails 4找不到关联has_many,通过:关系错误

相册样板

​​

功能模型

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: Could not find the association :join_table1 in model Album

这是为什么?

回答

13

您需要添加has_many :album_features既专辑和功能模型(假设您重命名JoinTable1模式更有意义AlbumFeature,以及相应的表将album_features),作为:through引用协会 - 你的错误也正是这件事。

或者您可以使用has_and_belongs_to_many,因此不需要定义特殊链接模型。但在这种情况下,您必须为您的表格命名为albums_features

+2

我不认为连接表的命名约定与has_many通过关系有关系。 – Starkers

+0

您不能拥有2个名称为Feature的模型,这是最重要的。 – biomancer

+0

另外,activerecord模型的名称应该与其表名相对应。 – biomancer

5

只要定义模型如下

相册样板

class Album < ActiveRecord::Base 
    has_many :join_table1 
    has_many :features, through: :join_table1 
end 

功能模型

class Feature < ActiveRecord::Base 
    has_many :join_table1 
    has_many :albums, through: :join_table1 
end 

join_table1模式

class JoinTable1 < ActiveRecord::Base 
    belongs_to :features 
    belongs_to :albums 
end 
0

同样喜欢@mad_raz回答,但连接表需要有英文单为belongs_to的,就像这样:

class JoinTable1 < ActiveRecord::Base 
    belongs_to :feature 
    belongs_to :album 
end 

完全协会教程https://kolosek.com/rails-join-table/

1

发生在我身上也。 通过将连接表作为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 

美国ge:

alert.incidents << incident 
alert.save!