首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在我的模型中包含了"has_many“,但是我会遇到一个has_many错误

在我的模型中包含了"has_many“,但是我会遇到一个has_many错误
EN

Stack Overflow用户
提问于 2018-04-18 17:23:05
回答 1查看 51关注 0票数 0

我正在使用Rails 5.1。我很困惑如何创建一个模型和关联,其中我有一个连接两个模型的联接表。下面是两个表的PostGres连接表.

代码语言:javascript
复制
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 |

所以我定义了这样的模型

代码语言:javascript
复制
class Organization < ApplicationRecord

  has_many :stratum_workers, :through => :organization_workers



class OrganizationWorker < ApplicationRecord
  belongs_to :organization
  belongs_to :stratum_worker
end

但是当我运行一个测试时

代码语言:javascript
复制
assert_false organization.stratum_workers.empty?, "A pre-condition of this test is thta the org have stratum workers."

我知道错误了

代码语言:javascript
复制
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>'
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-04-18 17:30:42

首先需要为联接表本身定义一个has_many,然后才能定义through关联。否则,Rails将不知道在哪里寻找桥梁。

你的加入模型看上去不错。但是你加入的模特应该是这样的:

代码语言:javascript
复制
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
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49905587

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档