我使用的是Rails 5.1。我很困惑如何创建一个模型和关联,其中我有一个链接两个模型的连接表。下面是两张表的PostGres连接表......
[AllowAnonymous]
[RoutePrefix("api/sandbox")]
public class SandboxApiController : ApiController
{
[HttpPost, Route("test")]
public IHttpActionResult Test()
{
throw new InvalidOperationException($"you screwed up. Local: {RequestContext.IsLocal}, IT: {User.IsInRole("IT")}");
}
}
那么我就像这样定义模型
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."
答案 0 :(得分:2)
您需要先为连接表本身定义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