我正在使用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>'发布于 2018-04-18 17:30:42
首先需要为联接表本身定义一个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
endhttps://stackoverflow.com/questions/49905587
复制相似问题