0

I use cancancan gem for role based authorization rules. I need to preform something like:

can :read, Post, Post.status = 1

This means that user can read post with status = 1. How can i do that?

Src
  • 5,252
  • 5
  • 28
  • 56

2 Answers2

1

According to the docs it should be as simple as

can :read, Post, status: 1

You must use database columns for these conditions (i.e. make sure status is a column in the posts table).

If this is not the case or you need something more complex than a hash of conditions, you can look into Defining Abilities with Blocks

Hope this helps.

Bart Jedrocha
  • 11,450
  • 5
  • 43
  • 53
  • uninitialized constant Post::Status. Status is column in posts table – Src Jun 28 '15 at 16:45
  • Are you putting `Status` with a capital s? It should be all lowercase (i.e. `status`) – Bart Jedrocha Jun 28 '15 at 16:51
  • Wat? Can you please post the full line of code you're using? – Bart Jedrocha Jun 28 '15 at 17:06
  • status written with capital s is from error output. – Src Jun 28 '15 at 17:13
  • controller: `authorize! :show, @post` ability.rb: `can :read, Post, status = 1` – Src Jun 28 '15 at 17:14
  • As the docs say, it's supposed to be a *hash* of conditions. So do `can :read, Post, status: 1` and *NOT* `can :read, Post, status = 1` – Bart Jedrocha Jun 28 '15 at 17:16
  • Sry i posteded code with mistake, i'm actually using code `can :read, Post, status: 1` – Src Jun 28 '15 at 19:06
  • Status is reserved word? Because if i'm using `id` or another field (even in block), everything works fine. Also, debug showed that status exists in passed Post variable. – Src Jun 28 '15 at 19:19
  • It isn't a reserved work. Not sure what is going with your code but if you can't figure it out, I would suggest posting a separate question. I've created a working sample app with what I described above and it works just fine. See it [here](https://github.com/bjedrocha/cancanoverflow) – Bart Jedrocha Jun 28 '15 at 21:32
  • I renamed column from `status` to `state` and everything working just fine, confused... – Src Jun 28 '15 at 21:38
  • It's hard to say without taking a looking at the rest of your code. If this answer helped you, please accept and upvote. Thanks. – Bart Jedrocha Jun 28 '15 at 22:02
0

Try

can(:read, Post, status: 1)
stoodfarback
  • 1,299
  • 9
  • 12
  • uninitialized constant Post::Status, my post controller: `authorize! :show, @post` – Src Jun 28 '15 at 13:51