gpt4 book ai didi

ruby-on-rails - 如何使用 "validates :attribute"引用父对象属性的值验证属性?

转载 作者:行者123 更新时间:2023-12-04 06:04:37 25 4
gpt4 key购买 nike

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

《飞行》 object [我使用 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

Ant 金服 “座位”目的:
# == 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 

但这会导致 名称错误 在座位 Controller 中:
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 异常(exception):
undefined method `flight' for #<Class:0x67e9b40>

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

进行这种验证的最佳做法是什么?

谢谢你。

- -编辑 - -

正如 Maurício Linhares 在下文中亲切地建议的那样,该问题可以通过定义 :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

再次感谢你。

最佳答案

你可以这样做:

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

因为方法 验证 在类级别被调用,所以没有 航类变量可用,因为它是一个实例变量。当你用 :baggage_allowance 配置它时,你告诉 Rails 在 的实例上调用 :baggage_allowance 方法座椅能够访问该值。

关于ruby-on-rails - 如何使用 "validates :attribute"引用父对象属性的值验证属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6875228/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com