gpt4 book ai didi

ruby-on-rails - 在销毁相关模型更新之前,错误不会传播

转载 作者:数据小太阳 更新时间:2023-10-29 07:18:33 26 4
gpt4 key购买 nike

我有一个父模型,它正在通过像“@client.update_attributes(params[:client]”这样的参数进行更新。在我的参数中是一个销毁“client_card”的调用。我在 client_card 上有一个 before_destroy 方法防止它被销毁等。我的 before_destroy 方法正在运行,但是,before_destroy 上的错误在更新时不会传播到相关模型。关于如何在更新时将此模型错误传播到关联模型有什么建议吗?

class Client < ActiveRecord::Base
has_many :client_cards, :dependent => :destroy
validates_associated :client_cards

class ClientCard < ActiveRecord::Base
belongs_to :client, :foreign_key => 'client_id'

attr_accessible :id, :client_id, :card_hash, :last_four, :exp_date

before_destroy :check_relationships

def check_finished_appointments
appointments = Appointment.select { |a| a.client_card == self && !a.has_started }
if(appointments && appointments.length > 0 )
errors.add(:base, "This card is tied to an appointment that hasn't occurred yet.")
return false
else
return true
end
end

end

最佳答案

我怀疑validates_associated只对 ClientCard 运行显式声明的验证,并且不会触发您在 before_destroy 中添加的错误打回来。您最好的选择可能是 before_update回调Client :

class Client < ActiveRecord::Base
has_many :client_cards, :dependent => :destroy

before_update :check_client_cards

# stuff

def check_client_cards
if client_cards.any_future_appointments?
errors.add(:base, "One or more client cards has a future appointment.")
end
end
end

然后 ClientCard :

class ClientCard < ActiveRecord::Base
belongs_to :client, :foreign_key => 'client_id'

# stuff

def self.any_future_appointments?
all.detect {|card| !card.check_finished_appointments }
end
end

关于ruby-on-rails - 在销毁相关模型更新之前,错误不会传播,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17031210/

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