正如標題所述,我正在尋找一種方法,允許我檢查在after_filter
中的動作(創建,更新,銷燬)是否成功。原因是我想要設置一個Flash消息並最終將create
和update
動作重定向到edit
而不是show。任何方式來檢查在after_filter操作是否成功?
目前我正在將此作爲controller
塊中的操作執行,但使用之前的過濾器會更容易,因爲在操作完成後我可以插入多個事件。
正如標題所述,我正在尋找一種方法,允許我檢查在after_filter
中的動作(創建,更新,銷燬)是否成功。原因是我想要設置一個Flash消息並最終將create
和update
動作重定向到edit
而不是show。任何方式來檢查在after_filter操作是否成功?
目前我正在將此作爲controller
塊中的操作執行,但使用之前的過濾器會更容易,因爲在操作完成後我可以插入多個事件。
看起來好像沒有簡單的方法。 我解決了可添加到控制器,並做了模塊如下:
module ActionStatus
[:create, :update, :destroy].each do |parsed_action|
define_method(parsed_action) do |&block|
super() do |success, failure|
@action_successful = failure.instance_of?(
InheritedResources::BlankSlate
) || failure.class.nil?
block.call(success, failure) unless block.nil?
end
end
end
def action_successful?
@action_successful = false if @action_successful.nil?
@action_successful
end
def action_failure?
!action_successful?
end
end
我知道支票上failure
類是可怕的,但它是唯一的髒和快速的黑客攻擊,使其工作。 注意,在使用模塊之前,模塊必須包含在其他模塊之前。
因爲我們已經在控制器中聲明瞭成功/失敗的聲明,所以我們應該避免重複這個工作。
您可以使用response.status
代碼來確定您的操作是否成功。這假定你遵循99%的時間我們做的約定。
class ApplicationController < ActionController::Base
after_action :maybe_flash
private
def succeeded?
response.status < 400 && response.status >= 200
end
def maybe_flash
# do something here
end
end
想象你有一個phones_controller.rb
高清更新 @phone = Phone.find(PARAMS [:編號])
respond_to do |format|
# if @phone.update_attributes(params[:phone])
if @phone.update_attributes phone_params
format.html { redirect_to @phone, notice: 'Phone was successfully updated.' }
format.json { render :show }
else
format.html { render action: "edit" }
format.json { render json: @phone.errors, status: :unprocessable_entity }
end
end
末
是status
告訴你一切你需要知道。