I know, I know, if you access Session-variables or Instance variables in
your Model you didn''t understand the MVC pattern and "should go
back to
PHP". But still, this could be very useful if you have - like us - a lot
of controllers and actions where you don''t always want to write
@current_account.object.do_something (not very DRY).
The solution I found is very easy:
Step 1: Add your current_account to Thread.current, so for example
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
Step 2: Add a current_account method to all your models
#/lib/ar_current_account.rb
ActiveRecord::Base.class_eval do
def current_account
Thread.current[:account]
end
end
Step 3: Voilá, in your Models you can do something like this:
class MyModel < ActiveRecord::Base
belongs_to :account
# Set the default values
def initialize(params = nil)
super
self.account_id ||= current_account.id
end
end
You could also work with something like the before_validation callback
in active_record and then make with a validation sure the account is
always set.
The same approach could be used if you always want to add the
current_user to every created object.
What do you think?
--
Posted via http://www.ruby-forum.com/.