【问题标题】:validate two foreign keys in the same table referencing the same table验证同一个表中引用同一个表的两个外键
【发布时间】:2016-09-29 14:21:56
【问题描述】:

我的表格卡片中有两个字段,user_idassignee_id。他们都在我的表用户中引用一个用户。需要第一个存在,但不需要第二个。

在我的验证中,我想检查第一个的完整性和是否存在,如果已填写,则只检查第二个的完整性。

我试过了,还是不行:

  belongs_to :user
  belongs_to :assignee, :class_name => 'User', :foreign_key => :assignee_id

  validates_presence_of [:title, :user_id]
  validates :user, presence: true
  validates :assignee_id

请问有谁知道如何正确操作吗? 提前谢谢你。

【问题讨论】:

    标签: mysql ruby-on-rails ruby validation ruby-on-rails-5


    【解决方案1】:

    在这种情况下,您通常会使用 ActiveRecord::Validations#validate 创建自定义验证。

    validates :user_id, presence: true
    validate  :integrity_of_assignee_id, if: ->(obj) { obj.assignee_id.present? }
    
    private
    
    def integrity_of_assignee_id    
      # Add error to the field if the `assignee_id` is invalid
      errors.add(:assignee_id, 'Not valid assignee_id') unless User.find_by(id: assignee_id)
    end
    

    【讨论】:

    • 感谢您的回答。这不允许我保存没有assignee_id 的对象,这不是我想要的。但是,此处检查了assignee_id 的完整性。
    • @VincentDéhaye 这是我从您的问题中了解到的,仅当存在user_id 时才验证assignee_id 的存在。你能解释一下我哪里弄错了吗?
    • assignee_id 只有在填写时才应检查,它的存在不是必需的,但 user_id 存在是必需的,因此它始终是填写的。两者之间没有任何关系。是不是更清楚了?如果是,我将编辑我的问题:)
    • @VincentDéhaye 还是您的意思是 assignee_id 应该对应于数据库中的现有对象?如果没有Assigneeassignee_id - 引发异常?乐
    • 我使用rescue 来捕获错误:) 请参阅:--- User.find(assignee_id) rescue ActiveRecord::RecordNotFound errors.add(:assignee_id, "Not valid assignee_id") rescue ActiveRecord:: RecordInvalid errors.add(:assignee_id, "Not valid assignee_id") end --- 我不编辑您的答案,因为我不确定这是最好的方法,但我知道 :) 也很高兴!再次感谢您!
    猜你喜欢
    • 2019-12-23
    • 1970-01-01
    • 2017-01-16
    • 1970-01-01
    • 2023-03-17
    • 2012-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多