is it possible to have conditional default scope in rails?

2.2k views Asked by At

I am on rails 3.2.21, ruby version is 2.0

My requirement is to have role based conditional default scope for a particular model. eg

consider role variable as an attribute of logged in user

if role == 'xyz'
  default_scope where(is_active: false)
elsif role == 'abc'
   default_scope where(is_active: true)
end
2

There are 2 answers

6
Andrey Deineko On BEST ANSWER

Nothing is impossible in programming.

Using default_scope is a bad idea in general (lots of articles are written on the topic).

If you insist on using current user's atribute you can pass it as an argument to scope:

scope :based_on_role, lambda { |role|
  if role == 'xyz'
    where(is_active: false)
  elsif role == 'abc'
    where(is_active: true)
  end
}

And then use it as follows:

Model.based_on_role(current_user.role)

Sidenote: Rails 3.2.x - seriously?...

2
Aleksei Matiushkin On
default_scope where(
  case role
  when 'xyz' then { is_active: false }
  when 'abc' then { is_active: true }
  else '1 = 1'
  end
)

Also, please read the answer by Andrey Deineko, specifically the part about default scopes usage.