Ruby on rails 检查父记录是否有任何子记录的开始日期在将来,然后停止更新rails
我有一个名为items的表,在items_controller.rb中有一个名为archive的方法,如果该方法被调用,它会将该项上的活动字段设置为false。问题是我有另一个名为reservations的表和一个名为start_date的字段,所以我想在它将item上的活动字段更新为false之前,我想检查它们是否有任何带有start_date字段的预订。如果存在,则不要更新项目上的活动字段,并向用户发送错误消息 这是item.rbRuby on rails 检查父记录是否有任何子记录的开始日期在将来,然后停止更新rails,ruby-on-rails,ruby,Ruby On Rails,Ruby,我有一个名为items的表,在items_controller.rb中有一个名为archive的方法,如果该方法被调用,它会将该项上的活动字段设置为false。问题是我有另一个名为reservations的表和一个名为start_date的字段,所以我想在它将item上的活动字段更新为false之前,我想检查它们是否有任何带有start_date字段的预订。如果存在,则不要更新项目上的活动字段,并向用户发送错误消息 这是item.rb class Item < ApplicationRec
class Item < ApplicationRecord
has_many :reservations
before_save :check_for_reservations
def check_for_reservations
if reservations.count > 0
reservations.each do |reservation|
if reservation.start_date > Date.today
return false
end
end
end
end
end
正在更新项目记录active equal=false时不起作用我认为使用自定义验证方法是合理的,您可以在。它可能看起来像这样:
class Item < ApplicationRecord
has_many :reservations
before_save :check_for_reservations
validate :okay_to_archive
def okay_to_archive
if !item.active && reservations.where("start_date >= ?", Date.today).any?
errors.add(:active, "can't be set to false when there are future reservations")
end
end
end
他们检查项目
是否在未来预订时处于非活动状态。如果是这样,则会将错误写入错误
:
errors.add(:active, "can't be set to false when there are future reservations")
当您尝试执行@item.save
时,将出现验证错误
def archive
@item = Item.find(params[:id])
@item.active = false
if @item.save
flash[:notice] = "Item been archived..."
else
flash[:alert] = "Something went wrong..."
end
redirect_back(fallback_location: request.referer)
end
代码未经测试,但应接近
errors.add(:active, "can't be set to false when there are future reservations")
def archive
@item = Item.find(params[:id])
@item.active = false
if @item.save
flash[:notice] = "Item been archived..."
else
flash[:alert] = "Something went wrong..."
end
redirect_back(fallback_location: request.referer)
end