gpt4 book ai didi

ruby-on-rails - 验证多列的 allow_blank

转载 作者:行者123 更新时间:2023-12-04 07:30:03 24 4
gpt4 key购买 nike

我根据它们的 active_state 验证 Realty 对象,所以如果它是 pending,多个字段可以是 blank

with_options :if => Proc.new { |a| a.active_state == 'pending'} do |realty|
realty.validates :street, :length => {:in => 1..100}, :allow_blank => true
realty.validates :postalcode, :numericality => {:only_integer => true}, :length => {:in => 4..5}, :allow_blank => true
realty.validates :city, :length => {:in => 1..50}, :allow_blank => true
realty.validates :description, :length => {:maximum => 8000}, :allow_blank => true
realty.validates :leasing_costs, :numericality => {:only_integer => true}, :length => {:in => 1..9}, :allow_blank => true
end

with_options :if => Proc.new { |a| a.active_state != 'pending'} do |realty|
realty.validates :street, :length => {:in => 1..100}
realty.validates :postalcode, :numericality => {:only_integer => true}, :length => {:in => 4..5}
realty.validates :city, :length => {:in => 1..50}
realty.validates :description, :length => {:maximum => 8000}
realty.validates :leasing_costs, :numericality => {:only_integer => true}, :length => {:in => 1..9}
end

唯一的区别是那些 :allow_blank => true 选项。

我想让这段代码更枯燥,所以我的尝试是使用一次正常的验证 block :

validates :street, :length => {:in => 1..100}
validates :postalcode, :numericality => {:only_integer => true}, :length => {:in => 4..5}
validates :city, :length => {:in => 1..50}
validates :description, :length => {:maximum => 8000}
validates :leasing_costs, :numericality => {:only_integer => true}, :length => {:in => 1..9}

然后在状态为 pending 的情况下简单地在所有这些字段上调用一些函数:

with_options :if => Proc.new { |a| a.active_state == 'pending'} do |realty|
realty.allow_blank_of :street, :postalcode, :city, :description, :leasing_costs
end

类似于所有那些 validates_uniqueness_of :x, :y, :z 方法。

我找不到适合我需要的功能。我该如何解决这个问题?

最佳答案

如果 :allow_blank 选项有一个 proc 就好了,但我不认为它有。但是,您可以使用 :if 选项获得相同的结果,因为 :allow_blank 本质上是一种表达“如果属性为空则不运行此验证要求”的方式”。所以试试这个:

with_options :if => Proc.new { |a| a.active_state == 'pending' ? a.present? : true } do |realty|
realty.validates :street, :length => {:in => 1..100}
realty.validates :postalcode, :numericality => {:only_integer => true}, :length => {:in => 4..5}
realty.validates :city, :length => {:in => 1..50}
realty.validates :description, :length => {:maximum => 8000}
realty.validates :leasing_costs, :numericality => {:only_integer => true}, :length => {:in => 1..9}
end

在这种情况下,proc 是说...如果 active_state'pending' 并且该属性存在,则执行此验证。但是,如果 active_state 不是 'pending',则该属性不允许为空,因此始终运行验证。我希望我根据您的需要得到了正确的逻辑。

关于ruby-on-rails - 验证多列的 allow_blank,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24713948/

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