【问题标题】:When does validate method get called in Rails?什么时候在 Rails 中调用 validate 方法?
【发布时间】:2016-06-23 08:36:59
【问题描述】:

我有一个模特StudentProductRelationship。我正在添加一个自定义验证器

validate :validate_primary_product , :if => "!primary_product"

方法是

def validate_primary_tag 
  unless StudentProductRelationship.exists?(:primary_product => true, :student_id => student_id)
    errors.add(:base,"There is no primary product associated to product")
  else
  end
end

primary_product 是一个布尔字段。我想为student_id 验证至少存在一个真实的primary_product。问题是如果我有一个StudentProductRelationship 对象说sprprimary_product = true。如果我这样做spr.update_attributes(primary_product: false)。验证不会引发错误,因为StudentProductRelationship.exists?(:primary_product => true, :student_id => student_id) 存在,因为spr 仍然存在于带有primary_product = true 的数据库中。如何超越?

【问题讨论】:

    标签: ruby-on-rails validation


    【解决方案1】:

    validates_presence_of :primary_product, scope: :student_id 不适合你吗?

    【讨论】:

    • 没有。不存在我需要它是true。这也可以处理false 对吗?
    猜你喜欢
    • 2016-12-19
    • 2011-07-21
    • 1970-01-01
    • 2015-07-13
    • 2012-11-30
    • 2016-05-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多