我的模型中包含 "has_many",但出现 "ActiveRecord::HasManyThroughAssociationNotFoundError" 错误
Included "has_many" in my model but I'm getitng a "ActiveRecord::HasManyThroughAssociationNotFoundError" error
我正在使用 Rails 5.1。我对如何创建模型和关联感到困惑,其中我有一个连接两个模型的连接 table。下面是我的 PostGres 连接 table 两个 tables ...
mydb=# \d organization_workers;
Table "public.organization_workers"
Column | Type | Modifiers
-------------------+---------+--------------------------------------------------------------
id | integer | not null default nextval('organization_workers_id_seq'::regclass)
organization_id | integer |
stratum_worker_id | integer |
然后我像这样定义模型
class Organization < ApplicationRecord
has_many :stratum_workers, :through => :organization_workers
class OrganizationWorker < ApplicationRecord
belongs_to :organization
belongs_to :stratum_worker
end
但是当我 运行 一个引用
的测试时
assert_false organization.stratum_workers.empty?, "A pre-condition of this test is thta the org have stratum workers."
我收到错误
Error:
OrganizationTest#test_Test_total_paid:
ActiveRecord::HasManyThroughAssociationNotFoundError: Could not find the association :organization_workers in model Organization
test/models/organization_test.rb:7:in `block in <class:organizationTest>'
您需要先为联接table本身定义一个has_many
,然后您可以定义through
关联。否则,Rails 将不知道去哪里寻找弥合差距。
您的连接模型看起来不错。但是您要加入的模型应该如下所示:
class Organization < ApplicationRecord
has_many :organization_workers
has_many :stratum_workers, through: :organization_workers
end
class StratumWorker < ApplicationRecord
has_many :organization_workers
has_many :organizations, through: organization_workers
end
我正在使用 Rails 5.1。我对如何创建模型和关联感到困惑,其中我有一个连接两个模型的连接 table。下面是我的 PostGres 连接 table 两个 tables ...
mydb=# \d organization_workers;
Table "public.organization_workers"
Column | Type | Modifiers
-------------------+---------+--------------------------------------------------------------
id | integer | not null default nextval('organization_workers_id_seq'::regclass)
organization_id | integer |
stratum_worker_id | integer |
然后我像这样定义模型
class Organization < ApplicationRecord
has_many :stratum_workers, :through => :organization_workers
class OrganizationWorker < ApplicationRecord
belongs_to :organization
belongs_to :stratum_worker
end
但是当我 运行 一个引用
的测试时assert_false organization.stratum_workers.empty?, "A pre-condition of this test is thta the org have stratum workers."
我收到错误
Error:
OrganizationTest#test_Test_total_paid:
ActiveRecord::HasManyThroughAssociationNotFoundError: Could not find the association :organization_workers in model Organization
test/models/organization_test.rb:7:in `block in <class:organizationTest>'
您需要先为联接table本身定义一个has_many
,然后您可以定义through
关联。否则,Rails 将不知道去哪里寻找弥合差距。
您的连接模型看起来不错。但是您要加入的模型应该如下所示:
class Organization < ApplicationRecord
has_many :organization_workers
has_many :stratum_workers, through: :organization_workers
end
class StratumWorker < ApplicationRecord
has_many :organization_workers
has_many :organizations, through: organization_workers
end