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

时间:2013-09-24 10:07:47

标签: ruby-on-rails ruby-on-rails-4 has-many-through

右。这简直就是拒绝工作。已经好几个小时了。

专辑型号

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 个答案:

答案 0 :(得分:18)

您需要将has_many :album_features添加到相册和要素模型中(假设您将JoinTable1模型重命名为更有意义的AlbumFeature,相应的表格将为album_features),因为:through引用关联 - 你的错误与此完全相同。

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

答案 1 :(得分:10)

只需将模型定义如下

专辑型号

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

答案 2 :(得分: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!

答案 3 :(得分:0)

同样像@mad_raz一样回答,但是联接表需要为belongs_to提供单数,如下所示:

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

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