How to make a user can only read his post?

59 Views Asked by At

I am a beginner of rails. I have created a new app, and then scaffold post, and then install devise & cancan. The tutorials that I could found are almost like this:

def initialize(user)
  user ||= User.new
  if user.admin?
    can :manage, Article
  else
    can :read, Article
  end
end

I don't want another users can reading the posts of my_own, I just want every user can only reading his posts. how can I do that? I hope a complete sample because I am a foolish guy. thanks a lot!

1

There are 1 best solutions below

0
On

You can pass in hash conditions e.g.

def initialize(user)
  user ||= User.new
  if user.admin?
    can :manage, Article
  else
    can :manage, Article, user_id: user.id
    can :read, Article
  end
end