我正在使用Rails 5.1。 我对如何创建一个模型和关联感到困惑,其中我有一个链接两个模型的连接表。 下面是我的两个表的 PostGres 连接表......
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>'
您需要首先为连接表本身定义一个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