I have a parent model, that is being updated via params like '@client.update_attributes(params[:client]'. In my params is a call to destroy a 'client_card'. I have a before_destroy method on the client_card that prevents it from being destroyed etc. My before_destroy method is working, however, the errors on the before_destroy do not propagate to the related model when updated. Any advice on how to propagate this model error to the associated model when updated?
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
I suspect that validates_associated
is only running the explicitly-declared validations for ClientCard
, and won't trigger off the errors you added in the before_destroy
callback. Your best option might be a before_update
callback on 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
Then on 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With