如何使用“validates:attribute”来引用父对象属性的值来验证属性?

时间:2011-07-29 15:11:52

标签: ruby-on-rails ruby-on-rails-3 validation customvalidator

O'Reilly的“Head first Rails”(编辑,2009)的练习中,有 2个相关对象

“Flight”对象[我使用annotate gem来显示每个属性]:

# == Schema Information
#
# Table name: flights
#
#  id                :integer         not null, primary key
#  departure         :datetime
#  arrival           :datetime
#  destination       :string(255)
#  baggage_allowance :decimal(, )
#  capacity          :integer
#  created_at        :datetime
#  updated_at        :datetime
#

class Flight < ActiveRecord::Base
  has_many :seats
end

蚂蚁“席位”对象:

# == Schema Information
#
# Table name: seats
#
#  id         :integer         not null, primary key
#  flight_id  :integer
#  name       :string(255)
#  baggage    :decimal(, )
#  created_at :datetime
#  updated_at :datetime
#

class Seat < ActiveRecord::Base
  belongs_to :flight
end

您可能猜测seat.baggage值应始终小于或等于seat.flight.baggage_allowance。

所以我写了这个验证器,效果很好:

class Seat < ActiveRecord::Base

  belongs_to :flight

  def validate
      if baggage > flight.baggage_allowance
      errors.add_to_base("Your have to much baggage for this flight!")
    end 
  end  
end

然后我尝试用这个更漂亮的那个重构它:

      validates :baggage, :numericality => { :less_than_or_equal_to => flight.baggage_allowance }, :presence => true 

但它在SeatsController中导致 NameError

undefined local variable or method `flight' for #<Class:0x68ac3d8>"

我还试过“self.flight.baggage_allowance”:

validates :baggage, :numericality => { :less_than_or_equal_to => self.flight.baggage_allowance }, :presence => true

但它会抛出 NoMethodError 例外:

undefined method `flight' for #<Class:0x67e9b40>

有没有办法让更漂亮的验证工作?

进行此类验证的最佳做法是什么?

谢谢。

--- --- EDIT

正如MaurícioLinhares在此后提出的那样,问题是可以解决的:定义:bagging_allowance符号。 我想更好地了解真正需要自定义验证的地方。 这个怎么样,是否可以将转换为“验证”方法?为什么?

class Seat < ActiveRecord::Base
.
.
.
def validate
  if flight.capacity <= flight.seats.size
    errors.add_to_base("The flight is fully booked, no more seats available!")
  end
end

再次感谢你。

1 个答案:

答案 0 :(得分:8)

你可以这样做:

class Seat < ActiveRecord::Base

  validates :baggage, :numericality => { :less_than_or_equal_to => :baggage_allowance }, :presence => true 

  belongs_to :flight

  def baggage_allowance
    flight.baggage_allowance
  end  
end

修改

你不能这样做:

class Seat < ActiveRecord::Base
        validates :baggage, :numericality => { :less_than_or_equal_to => flight.baggage_allowance }, :presence => true 
end

因为在类级别调用验证方法,所以没有 flight 变量可用,因为它是一个实例变量。使用:baggage_allowance进行配置时,您可以告诉Rails在 Seat 的实例上调用:baggage_allowance方法,以便能够访问该值。