Topic: Some questions about CanCan

Hi everybody,

(sorry for my English ;)

I started to use CanCan from rbates, this is awesome gem, but I have some problems:
I have Scrap model and there is boolean field :published (so, it means published/not published (draft)).

I have this rule in my ability.rb:
can :create, [Scrap]
can [:update, :destroy], [Scrap] do |object|
  object.try(:user) == user
end

So, this object cant be edited/updated/deleted by non-author. I want to do the same with my "show" action (non-author cant read drafts, really? ;) What is the true way to do this?

Thanx all!
Andrey Ognevsky

Last edited by elfxf (2010-07-06 14:12:22)

Re: Some questions about CanCan

I am not sure I completely understand what you want but I will take a stab ...

Non-authors can ONLY read a 'Scrap' if it is published (published == true) (let me know if my understanding is incorrect).

can :read, Scrap, :published => true

I got this syntax from http://wiki.github.com/ryanb/cancan/def … th-hashes.

Jeremiah

Re: Some questions about CanCan

jmesserer, thanks for your answer.
But what about author of this scrap? I want author to have ability to view any his scrap, but non-authors (this is not a separate role!) haven't.

Re: Some questions about CanCan

can :create, Scrap

can [:update, :destroy], Scrap do |object|
  object.try(:user) == user
end

can [:read], Scrap do |object|
  (object.try(:user) == user) || :published => true
end

Last edited by jmesserer (2010-07-09 09:59:01)

Re: Some questions about CanCan

I wrote the same, except 1 thing: :read is :index and :show, so I should write separate :index and :show action.
Thats ok, but what about controllers, I saw a method for controller, but it works when abilities are written in a hash-style (http://wiki.github.com/ryanb/cancan/fetching-records). Cant I write this block-styled abilities with a hash?

Re: Some questions about CanCan

Just a guess. Change it and see if it works, if it does then you can incorporate the controller methods.

can :read, Scrap,  (:user == user || :published => true)

Re: Some questions about CanCan

jmesserer wrote:

Just a guess. Change it and see if it works, if it does then you can incorporate the controller methods.

can :read, Scrap,  (:user == user || :published => true)

Thanks, I will try wink