【发布时间】:2015-05-17 01:21:43
【问题描述】:
def create
render json: '{"error": "400"}', status: :bad_request and return if post_params[:post].blank?
...and more general create code....
end
def update
render json: '{"error": "400"}', status: :bad_request and return if post_params[:post].blank?
...and more general update code....
end
如何从创建和更新操作中重构出上面的渲染错误 400 行,这样我就不会重复自己?
此验证将在我的代码中使用,我只想将其包含在我的操作中。
当我创建一个方法时,例如:
def validations
render json: '{"error": "400"}', status: :bad_request and return if post_params[:post].blank?
end
我看到一个错误:
AbstractController::DoubleRenderError (Render and/or redirect were called multiple times in this action. Please note that you may only call render OR redirect, and at most once per action. Also note that neither redirect nor render terminate execution of the action, so if you want to exit an action after redirecting, you need to do something like "redirect_to(...) and return".):
app/controllers/posts_controller.rb:43:in `create'
...当代码按上述方式简单编写时不存在。
【问题讨论】:
标签: ruby-on-rails controller refactoring render