フラッシュメッセージの代わりに赤いRails画面:RailsAdmin :: MainController#dashboardのCanCan :: AccessDenied

Aug 21 2020

Devise、CanCanCan、rails_adminを使用しています。アクセシビリティではすべて問題ありませんが、フラッシュメッセージを取得できず、root_pathにリダイレクトして、以下の画面を表示します。これの代わりにフラッシュメッセージを取得する方法についてのアイデア、ヒントはありますか?その他のフラッシュメッセージ、アラートと通知の両方がOKと表示されます。どうもありがとう。

私のApplicationControllerは次のとおりです。

class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
before_action :authenticate_user!

def after_sign_in_path_for(resource)
  stored_location_for(resource) || welcome_path_url
end

rescue_from CanCan::AccessDenied do |exception|
  respond_to do |format|
    format.json { head :forbidden, content_type: 'text/html' }
    format.html { redirect_to main_app.root_url, notice: exception.message }
    format.js   { head :forbidden, content_type: 'text/html' }
  end
end
end

rails_admin.rb

RailsAdmin.config do |config|

### Popular gems integration

## == Devise ==
config.authenticate_with do
  warden.authenticate! scope: :user
end
config.current_user_method(&:current_user)

## == CancanCan ==
# config.authorize_with :cancancan
config.authorize_with do
  redirect_to main_app.root_path unless current_user.superuser ==true
end
<....>
end

ability.rb

class Ability
  include CanCan::Ability

  def initialize(user)
    # Define abilities for the passed in user here. For example:
    #
    user ||= User.new # guest user (not logged in)
    if user.superuser?
      can :manage, :all
      cannot :access, :rails_admin
      cannot :manage, :dashboard
    end
    if user.office?
      cannot :access, :rails_admin
      cannot :manage, :dashboard
      can :read, :all
    end
  end
end

編集:実用的な答えがマークされています。また、次のようにステータス変数を定義する必要があります。

  def status
    @user_role ||= User.new(read_attribute(:user_role))
  end

私のUserモデルでは。

回答

2 user11350468 Aug 21 2020 at 23:11

RailsAdmin::MainControllerサブクラスで発生した例外をキャッチするためにアプリで定義したApplicationControllerから派生していないようです。

以下のような別の親コントローラーを使用するには、構成を明示的に追加する必要があります。ここで関連するgemドキュメントを見つけてください:

 # in config/initializers/rails_admin.rb

config.parent_controller = 'ApplicationController'

このスタックオーバーフローの答えもあなたを助けるかもしれません。