【发布时间】:2021-03-04 13:17:00
【问题描述】:
在我的 Rails 5.2 应用程序中,我有以下模型关系。
一个 Job 有很多 Contracts 和很多 Expertises。生成以下 Ruby on Rails 模型。
job.rb
class Job < ApplicationRecord
has_many :attached_expertises, as: :expertisable, dependent: :destroy
has_many :expertises, through: :attached_expertises
has_many :attached_contracts, as: :contractable, dependent: :destroy
has_many :contracts, through: :attached_contracts
end
contract.rb
class Contract < ApplicationRecord
has_many :attached_contracts, dependent: :destroy
end
attached_contract.rb
class AttachedContract < ApplicationRecord
belongs_to :contract
belongs_to :contractable, polymorphic: true
end
expertise.rb
class Expertise < ApplicationRecord
has_many :attached_expertises
end
attached_expertise.rb
class AttachedExpertise < ApplicationRecord
belongs_to :expertise
belongs_to :expertisable, polymorphic: true
end
我需要根据关联模型的值在 Job 中执行验证。 我也有 3 种 合同 和 3 种 专业知识。 假设合同可以是 P、C 或 E,而专业知识可以是 J、L、S。 如果选择 E 类型的 Contract,则创建或更新 Job 时,Expertise 必须是 类型J,否则如果应该引发错误。
我已经尝试过创建自定义验证 ActiveModel::EachValidator。但无法让它工作。在它自己的模型中也没有自定义方法。
实现这一目标的最佳方法是什么?
我应该在哪里放置验证器文件?在app/models/concerns/?
【问题讨论】:
标签: ruby-on-rails ruby model ruby-on-rails-5