我目前正在开发基于 Rails 3 构建的 Web 应用程序,该应用程序大量使用 Ajax/REST 作为客户端。因此,我经常发现自己编写这样的控制器操作:
def create
if !params[:name]
respond_to do |format|
format.html { render json: {}, status: :not_found }
format.json { render json: {}, status: :not_found }
end
return
end
account = ...
respond_to do |format|
format.html { render json: account }
format.json { render json: account }
end
end
几乎我所有的操作都是在成功案例或错误代码中返回一个 json 对象。但是,如果我希望动作更早地返回,我总是必须编写这个详细的 respond_to 块并返回。
相反,我想改用这样的东西,或者类似的替代方案:
def create
if !params[:name]
throw :not_found
end
account = ...
return account
end
Rails 3+ 如何做到这一点?