在我的模型中,法官与项目相关,因此:
class Judge < ApplicationRecord
has_and_belongs_to_many :projects
# ...
end
class Project < ApplicationRecord
has_and_belongs_to_many :judges
# ...
end
在SQL中表示为
CREATE TABLE public.judges_projects (
judge_id bigint NOT NULL,
project_id bigint NOT NULL
);
现在,我需要能够添加法官对他们评判的项目的反馈。我写了一个简单的迁移(add_column :judges_projects, :feedback, :string, default: ''
(,它产生了这个修改后的SQL:
CREATE TABLE public.judges_projects (
judge_id bigint NOT NULL,
project_id bigint NOT NULL,
feedback character varying DEFAULT ''::character varying
);
如何在不破坏现有判断和项目的情况下重构模型以包含额外字段?
它不会破坏评委和项目。你可以很好地使用它。
但是,如果您想获得feedback
,您需要为judges_projects
创建一个模型,因为它不是一个简单的联接表。
class Judge < ApplicationRecord
has_many :judges_projects
has_many :projects, through: :judges_projects
# ...
end
class Project < ApplicationRecord
has_many :judges_projects
has_many :judges, through :judges_projects
end
# You might want to rename the table to something more
# descriptive.
class JudgesProject < ApplicationRecord
belongs_to :judge
belongs_to :project
end
你可以要求judge.judges_projects.first.feedback
。