Ruby on rails 在关联模型更新时销毁之前,错误不会传播
我有一个父模型,它通过诸如'@client.update_attributes(params[:client]“。在我的参数中是一个销毁“客户机卡”的调用。我在客户机卡上有一个before_destroy方法,用于防止其被销毁等。我的before_destroy方法正在工作,但是,before_destroy上的错误在更新时不会传播到相关模型。有关如何将此模型错误传播到相关mo的建议del何时更新Ruby on rails 在关联模型更新时销毁之前,错误不会传播,ruby-on-rails,ruby,activerecord,Ruby On Rails,Ruby,Activerecord,我有一个父模型,它通过诸如'@client.update_attributes(params[:client]“。在我的参数中是一个销毁“客户机卡”的调用。我在客户机卡上有一个before_destroy方法,用于防止其被销毁等。我的before_destroy方法正在工作,但是,before_destroy上的错误在更新时不会传播到相关模型。有关如何将此模型错误传播到相关mo的建议del何时更新 class Client < ActiveRecord::Base has_many :
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
class客户端:destroy
验证关联的用户卡:客户端用户卡
类ClientCard'client\u id'
属性可访问:id、:客户端id、:卡片散列、:最后四个、:经验日期
销毁前:检查\u关系
def check_已完成约会
约会=约会。选择{a | a.client_card==self&&!a.has_start}
如果(约会和约会长度>0)
错误。添加(:base,“此卡与尚未发生的约会绑定。”)
返回错误
其他的
返回真值
结束
结束
结束
是否可能工作?如果控制器的删除操作像通常那样重定向到索引,您将永远看不到错误,因为重定向会重新加载模型。我怀疑validates\u associated
只运行显式声明的ClientCard
验证,而不会运行清除您在销毁之前的回调中添加的错误。您最好的选择可能是在客户端上进行更新之前的回调:
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
否。我已使用调试器。这不在客户端卡的删除中,而是在父模型(客户端)控制器的更新方法中。调用client.update\u参数,客户端没有错误(即使参数说要销毁关联对象,例如客户端卡)好吧,如果客户端有未来约会的客户端卡,我不想阻止客户端被更新,但是如果更新包含对客户端卡嵌套属性的销毁,我确实想阻止客户端更新。然后,如果客户端卡有未来约会,我想抛出一个错误,等等。
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