視頻:https://gorails.com/episodes/actionable-errors-in-rails-6?autoplay=1html
這篇視頻介紹了Rails6的一個新功能:git
這個模塊定義一個action來解決各類錯誤類型。經過在❌提示網頁上添加了一個button按鈕。一鍵處理相關的❌。github
定義了一個"Run pending migrations" , 當遇到PendingMigrationError後,執行action塊內的命令。app
# class PendingMigrationError < MigrationError # include ActiveSupport::ActionableError # # action "Run pending migrations" do # ActiveRecord::Tasks::DatabaseTasks.migrate # end # end
<% actions = ActiveSupport::ActionableError.actions(exception) %> <% if actions.any? %> <div class="actions"> <% actions.each do |action, _| %> <%= button_to action, ActionDispatch::ActionableExceptions.endpoint, params: { error: exception.class.name, action: action, location: request.path } %> <% end %> </div> <% end %>
button_to生成一個帶一個button的form。用於提交由一系列options建立的URL。less
這個模塊的call調用ActionableError.dispatch方法執行自定義的塊內的命令。this
def call(env) request = ActionDispatch::Request.new(env) return @app.call(env) unless actionable_request?(request) ActiveSupport::ActionableError.dispatch(request.params[:error].to_s.safe_constantize, request.params[:action]) redirect_to request.params[:location] end
//1 rails g scaffold Post title //2 打開本地網頁localhost:300,因爲沒有執行rails db:migrate會報❌ //ActiveRecord::PendingMigrationError //Migrations are pending. To resolve this issue, run: rails db:migrate RAILS_ENV=development //而後附加一個按鈕 "Run pending migrations"
點擊這個按鈕後會執行:migrate命令,能夠在terminal上看到Migrating to CreatePosts (20190509031430).spa
在PostsController內添加一個對NoDataError類型錯誤的一鍵處理。code
class PostsController < ApplicationController ... class NoDAtaError < StandardError include ActiveSupport::ActionableError action "Run seeds" do Rails.application.load_seed end end
def index
@posts = Post.all
raise NoDataError if @posts.none?
end orm
進入localhost:3000/posts, 若是沒有數據post就會進入❌頁面,並添加一個button。
添加種子:在seeds.rb內添加:Post.create(title:"hello Error!")。
點擊button,後會運行塊內的load_seed命令。並從新渲染網頁。