5

我有一个父模型,它正在通过像'@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
4

2 回答 2

2

我怀疑这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
于 2013-06-10T21:42:46.827 回答
0

有可能它正在工作吗?如果您的控制器的删除操作像通常那样重定向到索引,您将永远不会看到错误,因为模型是通过重定向重新加载的。

于 2013-06-10T19:39:48.897 回答