嵌套资源被销毁,但关联的模型应避免这种情况(Rails 5中的验证)

时间:2019-07-09 09:07:38

标签: ruby-on-rails validation ruby-on-rails-5 nested-attributes

我有一个TimeWorked类,与has_oneEvent(一个或零个)关系

Event在我的控制器中作为TimeWorked的nested_resource进行操作,并且可以很好地用于创建和更新。

我对TimeWorked进行了验证,以防止在对对象进行签名(最终)时进行修改(更新或销毁)。

我遵循了所有更新的答案(因为Rails 5改变了chain_halted的工作方式),我可以在SO上找到

到目前为止,我可以防止我的主模型TimeWorked被破坏或更新,但是即使使用throw(:abort) ActiveRecord仍在破坏我的关联资源TimeWorkedEvent

如何防止此模型及其嵌套资源被破坏?

模型(TimeWorked / Event / Join table):

class TimeWorked < ApplicationRecord
  has_one :time_worked_event, dependent: :destroy
  has_one :event, through: :time_worked_event
  accepts_nested_attributes_for :time_worked_event, reject_if: proc {|att| att[:event_id].blank?}

  # cannot destroy timeworked that has been signed
  before_destroy do
     not_signed
     throw(:abort) if errors.present?
  end

 def not_signed
    errors.add(:signed, "Cannot modify or destroy a signed timeworked") if signed_exist?
  end

end

class Event < ApplicationRecord
end

class TimeWorkedEvent < ApplicationRecord
  belongs_to :event
  belongs_to :time_worked
  validates_presence_of :event
  validates_presence_of :time_worked
  validates_uniqueness_of :time_worked_id
end

控制器:

class TimeWorkedController < ApplicationController
 def destroy
    @time_worked.destroy
  end
end

1 个答案:

答案 0 :(得分:1)

之所以发生这种情况,是因为before_destroy在相依对象之后运行:销毁回调。因此,您可以执行以下操作以在依赖之前调用它:destroy-

  before_destroy :check, prepend: true

  def check
    not_signed
    throw(:abort) if errors.present?
  end