【问题标题】:Rails 5 model custom validation with relation has manyRails 5 模型自定义验证与关系有很多
【发布时间】: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


    【解决方案1】:

    您可以使用validates_with 并编写自定义方法来进行检查

    class Person < ActiveRecord::Base
      validates_with GoodnessValidator
    end
    
    class GoodnessValidator < ActiveModel::Validator
     def validate(record)
      if record.first_name == "Evil"
       record.errors[:base] << "This person is evil"
      end
     end
    end 
    

    【讨论】:

    • 我正在尝试这样做,但我收到错误 uninitialized constant Job::Contracts。我的验证器在文件夹 app/models/concerns/ 中,带有 class Contracts &lt; ActiveModel::Validator,在我的模型中,我有 include ActiveModel::Validationsvalidates_with Contracts 我哪里错了?
    • FIXED:这是一个命名约定问题,验证器文件需要命名为contracts.rb,它被命名为contracts_validator.rb
    猜你喜欢
    • 1970-01-01
    • 2018-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-30
    相关资源
    最近更新 更多