0

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
Andrey Deineko
  • 51,333
  • 10
  • 112
  • 145
srikant
  • 260
  • 3
  • 11

2 Answers2

2

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?...

Andrey Deineko
  • 51,333
  • 10
  • 112
  • 145
1
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.

Aleksei Matiushkin
  • 119,336
  • 10
  • 100
  • 160
  • I think it will just throw `undefined variable or method 'role' for Model` – Andrey Deineko Sep 07 '16 at 07:21
  • Once again, as I have said in the comment to your answer, there is a significant difference between static and dynamic clauses. This one is static, it’s evaluated in model’s context once. – Aleksei Matiushkin Sep 07 '16 at 07:26