关于has_many,我有三个问题:通过关系,以及一些错误,我不明白我正在尝试创建的设置。首先,我将描述我设置的内容:
我有一个任务模型
class Task < ApplicationRecord
has_many :task_standards
has_many :standards, through: :task_standards
end和一个标准模型
class Standard < ApplicationRecord
has_many :task_standards
has_many :tasks, through: :task_standards
end我需要一种任务和标准之间的关系,这个关系也有另一个领域,所以我生成了一个TaskStandard模型。
class TaskStandard < ApplicationRecord
belongs_to :task
belongs_to :standard
end创建了一个迁移20190704213323_create_task_standards.rb。
class CreateTaskStandards < ActiveRecord::Migration[5.2]
def change
create_table :task_standards do |t|
t.belongs_to :task, index: true
t.belongs_to :standard, index: true
t.string :level
t.timestamps
end
end
end我可以在数据库中看到task_standards表
Table "public.task_standards"
Column | Type | Collation | Nullable | Default
-------------+-----------------------------+-----------+----------+--------------------------------------------
id | bigint | | not null | nextval('task_standards_id_seq'::regclass)
task_id | bigint | | |
standard_id | bigint | | |
level | character varying | | |
created_at | timestamp without time zone | | not null |
updated_at | timestamp without time zone | | not null |
Indexes:
"task_standards_pkey" PRIMARY KEY, btree (id)
"index_task_standards_on_standard_id" btree (standard_id)
"index_task_standards_on_task_id" btree (task_id)我运行了我的测试,但是我得到了错误:ActiveRecord::StatementInvalid: ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR: relation "standards_tasks" does not exist。我已经删除并创建了测试和开发环境数据库,并回滚并重新运行迁移。
我去了Rails控制台,尝试创建一个任务,并将任务标准设置为一个新任务数组,但是控制台给出了错误,ActiveRecord::HasManyThroughAssociationNotFoundError (Could not find the association :standard_tasks in model Task) .如果我试图创建一个标准并将任务添加到其中,我会得到同样的结果,但是相反:(Could not find the association :task_standards in model Standard)
我的问题是:
could not find the association :standard_tasks in model Task放在控制台中,我还没有在has_many :task_standards和task.rb中添加它。我所有的都是has_many :standards, through :task_standards (呵呵!)更新:我发现了测试中"standards_tasks“的问题来自哪里:我有一个在固定环境中创建standards_tasks.yml的旧模型生成,当我销毁该迁移/模型时,它没有被删除。
发布于 2019-07-05 15:22:01
测试(ActiveRecord::StatementInvalid: ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR: relation "standards_tasks" does not exist)的问题出现在一个被破坏的先前模型生成遗留的文件中。在测试/夹具中有一个standards_tasks.yml文件。当我删除那个.yml文件时,测试按预期运行。
控制台中的could not find the association :standard_tasks in model Task问题是由于在我所关联的模型中不包括关系表本身造成的。虽然我有has_many :tasks, through :task_standards,但我还没有在我的standard.rb和task.rb中添加has_many :task_standards。
https://stackoverflow.com/questions/56895265
复制相似问题