我正在努力使它在任何给定的时间只能填充三列中的一列。
以下是我所想的一些伪代码:

class Model < ActiveRecord::Base
  validates :column_one, presence: true,
    absence: true if (:column_two.present? || :column_three.present?)
  validates :column_two, presence: true,
    absence: true if (:column_one.present? || :column_three.present?)
  validates :column_three, presence: true,
    absence: true if (:column_one.present? || :column_two.present?)
end

是否可以在模型级别执行此操作,或者我只需在控制器或参数中管理它?

最佳答案

要在不重复代码的情况下签入单个验证,请使用自定义验证方法:

class Model < ActiveRecord::Base
  validate :there_can_be_only_one
end

def there_can_be_only_one
  if [column_one, column_two, column_three].count(&:present?) > 1
    column_with_error = column_one.present? ? :column_one : :column_two
    errors.add(column_with_error,
      "can't be present if any other column in [column_one, column_two, column_three] is also present"
  end
end

关于ruby-on-rails - 一次仅允许ActiveRecord模型中的多个属性之一,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35965456/

10-10 09:19