如果 create/update/destroy 操作在没有回调的情况下成功,则执行一些代码

Execute some code if create/update/destroy action is successful without callbacks

现在我有一个模型 Trip,保存后,运行 有一些回调。我想隔离此行为,以便它仅在控制器上 运行 时发生 (create/update/destroy),因此我想删除回调。

假设我有一个服务对象 DoSomething#call 它接受 trip 并做我需要的一切,我在 create/update/destroy 中 运行 它有什么选择?

我有一些想法,但它们涉及恐怖的事情,例如:

def create
  super() do |success, failure|
    @action_successful = failure.instance_of?(
      InheritedResources::BlankSlate
    ) || failure.class.nil?
    if @action_successful
      DoSomething.call(Trip.find(params[:id]))
    end
  end
end

它有很多缺点:

请求的附加代码

class Trip
end

定制服务(我有多个)

class SaveLastChangedTrip
  def call(user, trip)
    return if user.nil?
    user.update_attributes!(last_trip: trip)
  end
end

和 activeadmin 文件

ActiveAdmin.register Trip do
  controller do
    def update
      if super() # This is pseudocode, I want to run this branch only if save is successful
        SaveLastChangedTrip.call(current_user, resource)
      end
    end
  end
end

我想你正在寻找这样的东西:

    def create
      create! do |success, failure|
        success.html do
          DoSomething.call(resource)
        end
      end
    end

有关类似示例,请参阅 comments.rb