views:

21

answers:

1

I am trying to create a scope on a model of mine limiting the available results to only those that are owned by the user's partner. When the user is an administrator, however, I want all models to be available. This works, but looks stupid. What is the proper rails3 way of expressing this?

scope :accessible_by, proc { |user|
  if user.admin?
    where("1=1")
  else
    where(:owner_id => user.partner.id)
  end
}

What I want to be able to do is select further and do e.g

@models = MyModel.
            accessible_by(current_user).
            other_scope.
            where(:property => value).
            order("another_property desc").
          all
+1  A: 

You might be able to use the all modifier.

scope :accessible_by, proc { |user|
  if user.admin? == false
    where(:owner_id => user.partner.id)
  end
}
davydotcom
Didn't know about #all. Thanks!
François Beausoleil
that triggers the query though, and doesn't let me build on it further
ormuriauga
Dont even need all. Simply dont specify an else condition. All a named scope does is simply fire a method within the ActiveRecord Object. For example, if the user.admin? == false then you want to fire the where method...Otherwise you don't need to tack on any where clause.
davydotcom