在相关模型更新销毁之前,错误不会传播
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在相关模型更新销毁之前,错误不会传播相关的知识,希望对你有一定的参考价值。
我有一个父模型,通过诸如'@ 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
另一答案
它可能有效吗?如果您的控制器的删除操作正常重定向到索引,则您将永远不会看到错误,因为重定向会重新加载模型。
以上是关于在相关模型更新销毁之前,错误不会传播的主要内容,如果未能解决你的问题,请参考以下文章