新手问题 求问 validates 问题 两个 model 参数比较

eastfox2002 · 2013年07月18日 · 最后由 zlx_star 回复于 2013年07月19日 · 2340 次阅读

我现在有 seat 和 flight 两个 model 定义了 flight has_many seats seat belongs_to flight 我想验证 seat 中的 baggage 小于 flight 中的 baggage_allowance,网上找了半天,怎么试都失败 我写的代码 validates :baggage, :numericality =>{:less_than => flight.baggage_allowance } 把 flight.baggage_allowance 换成数字就能执行,现在这样不行 求指教,谢谢

试试用 lambda

validates :baggage, numerically: { less_than: -> { flight.baggage_allowance } }

#1 楼 @ashchan 谢谢,不过测试了下,还是失败了

#2 楼 @eastfox2002 那就写个方法。

validate :check_baggage_allowance

def check_baggage_allowance
  baggage < flight.baggage_allowance
end
validate :ensure_baggage_not_too_large

private
def ensure_baggage_not_too_large
  return true if self.flight.nil?

  if self.baggage >= self.flight.baggage_allowance
    self.errors.add(:baggage, "is too large for the flight")
    return false
  end

  true
end

#3 楼 @ashchan 果然要写方法啊。。。成功了,谢~~

validates :baggage, numerically: { less_than: -> { flight.baggage_allowance } }

的问题可能在于创建时还没有关联的 flight, 试试

validates :baggage, numerically: { less_than: -> { flight.baggage_allowance } }, unless: "flight.nil?"
需要 登录 后方可回复, 如果你还没有账号请 注册新账号