我知道,我知道,如果您在模型中访问会话变量或实例变量,那么您不了解 MVC 模式并且“应该回到 PHP”。但是,如果您像我们一样拥有很多控制器和操作,但您并不总是想编写 @current_account.object.do_something(不是很干),这仍然非常有用。
我找到的解决方案非常简单:
第 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 添加到每个创建的对象,则可以使用相同的方法。
你怎么看?