gpt4 book ai didi

ruby-on-rails - 如何在 ruby​​ 中的特定条件后结束每个循环

转载 作者:太空宇宙 更新时间:2023-11-03 17:22:03 25 4
gpt4 key购买 nike

我已经包含了给定的代码

  def check_ip
start_ip = IPAddr.new(myip).to_i
end_ip = IPAddr.new(endip).to_i
ip_pool = IpTab.all
p '!!!!!!!!!!!!!!!!!!!!!!!'
p ip_pool
ip_pool.each do |ip|
low = IPAddr.new(ip.start_ip).to_i
high = IPAddr.new(ip.end_ip).to_i
p '-------------------------------'
p ((low..high)===start_ip)
p ((low..high)===start_ip)
p '******************************'
break if (low..high)===start_ip
break if (low..high)===end_ip
p '*******************************'
self.errors.add(:start_ip, I18n.t('errors.start_ip'))

end
end

我得到给定的输出:

"!!!!!!!!!!!!!!!!!!!!!!!"
IpPool Load (0.1ms) SELECT `ip_pools`.* FROM `ip_pools`
#<ActiveRecord::Relation [#<IpPool id: 1, start_ip: "10.10.10.10", end_ip: "10.10.10.20", user_id: 1, created_at: "2015-09-08 05:12:34", updated_at: "2015-09-08 05:12:34">, #<IpPool id: 4, start_ip: "11.12.12.13", end_ip: "11.12.12.16", user_id: 1, created_at: "2015-09-08 06:08:38", updated_at: "2015-09-08 06:08:38">]>
"-------------------------------"
true
true
"******************************"

但如果我的 start_ip 或 end_ip 位于数据库中给定的 ip 之间,则它不起作用我想它不允许保存 ip。即,如果 (low..high)===start_ip 或如果 (low..high)===end_ip 为真,则不允许保存。
指导我如何解决此问题,因为我的代码无法正常工作指导我如何编写此代码。

最佳答案

if (low..high)===start_ip or if (low..high)===end_ip is true it would not allow to save

你的循环不是那样工作的。假设 (low..high)===start_iptrue。你的循环变成:

ip_pool.each do |ip|
low = IPAddr.new(ip.start_ip).to_i
high = IPAddr.new(ip.end_ip).to_i
break if true # loop exits here
break if (low..high)===end_ip # not called
self.errors.add(:start_ip, I18n.t('errors.start_ip')) # not called either
end

如果 if (low..high)===end_iptrue,则变为:

ip_pool.each do |ip|
low = IPAddr.new(ip.start_ip).to_i
high = IPAddr.new(ip.end_ip).to_i
break if (low..high)===start_ip # nothing happens
break if true # loop exits here
self.errors.add(:start_ip, I18n.t('errors.start_ip')) # not called
end

无论哪种方式,self.errors.add 都不会被调用。但是,如果两个条件都为 false,它会被调用,这可能不是您想要的。

要解决你的问题,你可以这样写:

ip_pool.each do |ip|
low = IPAddr.new(ip.start_ip).to_i
high = IPAddr.new(ip.end_ip).to_i

if (low..high).include?(start_ip) || (low..high).include?(end_ip)
errors.add(:start_ip, I18n.t('errors.start_ip'))
break
end
end

或者有单独的错误:

ip_pool.each do |ip|
low = IPAddr.new(ip.start_ip).to_i
high = IPAddr.new(ip.end_ip).to_i

if (low..high).include?(start_ip)
errors.add(:start_ip, I18n.t('errors.start_ip'))
break
elsif (low..high).include?(end_ip)
errors.add(:end_ip, I18n.t('errors.end_ip'))
break
end
end

请注意,我已将 rng===obj 替换为 rng.include?(obj)

此外,我认为您的before_save :check_ip 应该是一个validate :check_ip,如Performing Custom Validations 所示。 .该文档还展示了如何实现可应用于多个属性的 EachValidator

关于ruby-on-rails - 如何在 ruby​​ 中的特定条件后结束每个循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32450533/

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