Model -> with_scope -> session access?


I try to override the default find method for some of my models:

I want it to find only the users, which belong to a specific customer.
Therefore I set an application-wide instance variable before rendering
anything else:

class ApplicationController < ActionController::Base
before_filter :cid, :uid

def cid
@cid ||= session[:customer_id] if logged_in?

My model should do the following (but it doesnt work this way):

class User < ActiveRecord::Base
with_scope :find, :conditions => {:customer_id = cid}


I know that accessing the session in models isn’t beatifull - so I
tied via the application-method…
Can somebody help me?

Thanks a lot!
Best regards

Can somebody help me?

Got named scopes?

Yeah, but this ins’t working either… When i try with:

class User < ActiveRecord::Base
with_scope :owning, :conditions => {:customer_id = cid}


the following error occurs:

** Starting Rails with development environment…
base.rb:1667:in method_missing_without_paginate': undefined local variable or methodcid’ for #Class:0x23ae54c (NameError)

Or do I missunderstand you? (sorry, my english is very bad)

Doesnt’t have anyone an idea?
Please help me, I think that other people are interessted in a
solution too…

Lp wrote:

Doesnt’t have anyone an idea?

There may be no advanced solution. The simple solution might be to pass
cid as
an argument to a method on a model:

class User < ActiveRecord::Base
def find_owners(cid)
find(:all, :conditions => {:customer_id => cid})


From there, what more do you need?


if you meant

class User < ActiveRecord::Base
NAMED_scope :owning, :conditions => {:customer_id = cid}


this is producing the same error like above…

Heeeelp :frowning:
Or are there any other solutions (no I don’t want to pass the id
everytime… It’s not very DRY i think…)?

Maybe I’m oversimplifying, but the general approach for scoping is

has_many :customers

Things are scoped already via your associations. No need to use

@user = current_user
@customers = @user.customers

@user = User.find(params[:user_id[
@customers = @user.customers.find(:all, :conditions => ["last_contacted

?", 10.days.ago], :order => “last_name ASC”, :limit => 100

So… Would that work? A lot of this could be done dynamically too,
some basic metaprogramming.


I haven’t see the wood for the trees ^^

That’s a quite good solution - I get everytime the current user in the
application-controller and use it in every action…


Yeah, that’s propably a solution (and the solution I’m currently
using) - but that’s not very DRY…

I have about 6 models and 40 actions… and in every action I do
something similar because of the rights/access-management:

Model.find(xyz, :condition => {:customer_id =>


I don’t think it’s very DRY…?
I can’t imagin that there isn’t a solution for it - that’s a common
problem in my opinion?