Devise を使用してユーザーを認証しています。すべてのテーブルで global_location_id 列に基づいてデータを表示/非表示にする必要があります。現在の global_location_id の値は current_user.global_location_id から取得されます。モデルの 1 つに次のデフォルト スコープを追加しようとしました。
class Artifact < ActiveRecord::Base
default_scope where(:global_location_id => current_user.global_location_id)
しかし、次のエラーが発生します。
undefined local variable or method `current_user' for #<Class:0x8721840>
モデルで current_user が使用できないことを回避するために、アプリケーションコントローラーに以下を追加しました
class ApplicationController < ActionController::Base
def set_global_location_id
@global_location_id = current_user.global_location_id
end
そして、コントローラーからメソッドを呼び出しました
class ArtifactsController < ApplicationController
#Check to see if the user is logged in first
before_filter :authenticate_user!
before_filter :set_global_location_id
@global_location_id を追加するようにモデルのデフォルト スコープを変更しました
class Artifact < ActiveRecord::Base
default_scope where(:global_location_id => @global_location_id)
しかし、これもうまくいきません。@global_location_id は、アプリケーション コントローラーで適切に設定されています。しかし、モデルでは空です。それを機能させる方法。