Ruby on Rails - Access controller variable from model Ruby on Rails - Access controller variable from model ruby ruby

Ruby on Rails - Access controller variable from model


You shouldn't generally try to access the controller from the model for high-minded issues I won't go into.

I solved a similar problem like so:

class Account < ActiveRecord::Base  cattr_accessor :currentendclass ApplicationController < ActionController::Base  before_filter :set_current_account  def set_current_account    #  set @current_account from session data here    Account.current = @current_account  endend

Then just access the current account with Account.current


DISCLAIMER: The following code breaks MVC conventions, that said...

Using class attributes can probably lead to thread safety issues. I would use Thread.current + around_filter to store controller related data at thread level, and ensure it gets clearedjust before the request finishes:

class ApplicationController < ActionController::Base  around_filter :wrap_with_hack  def wrap_with_hack    # We could do this (greener solution):     # http://coderrr.wordpress.com/2008/04/10/lets-stop-polluting-the-threadcurrent-hash/    # ... but for simplicity sake:    Thread.current[:controller] = self    begin      yield    ensure     # Prevent cross request access if thread is reused later     Thread.current[:controller] = nil    end  endend

Now the current controller instance will be avaliable globaly during the request processing through Thread.current[:controller]


If you need to access a controller variable from a model it generally means your design is wrong because a controller serves as bridge between view and model (at least in Rails), controller gets info from models, models shouldn't know anything about controllers, but if you want to do it anyway you can do it just as jeem said, but I'd rather do:

 class << self    attr_accessor :current end

instead of

cattr_accessor :current

you can see why here => cattr_accessor doesn't work as it should