Rails 4 before_destroy不会阻止破坏

时间:2014-06-25 15:49:54

标签: ruby-on-rails ruby-on-rails-4

这是我设置的简单消息模型。

class Message < ActiveRecord::Base

  validates_presence_of :user_id, :head, :text

  belongs_to :user

  has_many :receivers, class_name: MessageReceiver
  has_many :users, through: :receivers

  before_destroy :check_receivers

  private

  def check_receivers
    if self.receivers.empty?
      true
    else
      self.update(deleted: 1)
      false
    end
  end

end

:check_receivers方法在直接调用时按预期工作(我将其从私有部分删除,但是它不会阻止消息被破坏。

我在这里做错了吗?

1 个答案:

答案 0 :(得分:0)

删除

before_destroy :check_receivers

并尝试

has_many :receivers, class_name: MessageReceiver, dependent: :restrict_with_exception