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

问题描述 投票:13回答:4

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

专辑模型

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

为什么是这样?

ruby-on-rails ruby-on-rails-4 has-many-through
4个回答
18
投票

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

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


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

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!

0
投票

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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.