16

对。这只是拒绝工作。一直在这几个小时。

专辑模特

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

为什么是这样?

4

4 回答 4

24

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

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

于 2013-09-24T10:14:16.530 回答
15

只需定义模型如下

专辑模特

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
于 2016-04-17T19:57:45.030 回答
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

用法:

alert.incidents << incident
alert.save!
于 2018-01-25T12:24:05.667 回答
0

与@mad_raz 回答类似,但连接表需要为 belongs_to 提供单数,如下所示:

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

完整的关联教程https://kolosek.com/rails-join-table/

于 2017-09-02T23:22:48.717 回答