モデルでセッション変数またはインスタンス変数にアクセスする場合、MVC パターンを理解していないため、「PHP に戻る必要があります」。それでも、私たちのように、常に @current_account.object.do_something を書きたくない (あまり DRY ではない) コントローラーとアクションがたくさんある場合、これは非常に便利です。
私が見つけた解決策は非常に簡単です:
ステップ 1: current_account を Thread.current に追加します。たとえば、
class ApplicationController < ActionController::Base
before_filter :get_current_account
protected
def get_current_account
# somehow get the current account, depends on your approach
Thread.current[:account] = @account
end
end
ステップ 2: すべてのモデルに current_account メソッドを追加する
#/lib/ar_current_account.rb
ActiveRecord::Base.class_eval do
def self.current_account
Thread.current[:account]
end
end
ステップ 3: ほら、モデルで次のようなことができます。
class MyModel < ActiveRecord::Base
belongs_to :account
# Set the default values
def initialize(params = nil)
super
self.account_id ||= current_account.id
end
end
また、active_record の before_validation コールバックのようなものを使用して、アカウントが常に設定されていることを検証して確認することもできます。
作成されたすべてのオブジェクトに常に current_user を追加する場合は、同じアプローチを使用できます。
どう思いますか?