0

This might be a bit of a noob question, but I'm asking anyway.

So I'm building an app where people make posts. So it's a social network.

But I don't want people to be able to edit and delete other's posts.

I don't think a role-based system would work here, because people only administrate their own posts only.

I was thinking some sort of AR association, but I don't know if that would work.

What I want is something like this for my app/models/ability.rb:

class Ability
  def initialize(user)
    if current_user.username == @post.username
      can :edit, Post
      can :destroy, Post
    end
  end 
end

How would I go about doing this (assuming the models are User and Post)?

So basically should I do a User has Posts, or User has and belongs to Posts?

weddingcakes
  • 653
  • 1
  • 7
  • 14
  • What problems are you actually having? Have you tried that? Also, don't you associate a user to the post? Why not `current_user == @post.user`. Or `@post.owner` – Ismael Abreu Nov 18 '12 at 16:57
  • @IsmaelAbreu The question is how I would go about doing that, e.g. `has_many`, `has_one`, `has_and_belongs_to_many`. – weddingcakes Nov 18 '12 at 17:04

2 Answers2

2

Use this

class Ability
  def initialize(user)
    can [:edit, :destroy], Post do |post|
      post.try(:user) == user
    end
  end 
end
mike
  • 749
  • 10
  • 21
0

The problem is that class Ability won't have access to the @post instance variable. So I think in Ability.rb you would have to say that users can :manage, Post so they can create, edit and destroy Post objects. Then it's up to your controller and model layers to ensure that they can only edit and destroy their own Posts.

With CanCan you can call load_and_authorize_resource at the top of a controller to protect the entire thing, but in your case your PostsController will probably need to protect at the action level. Calling authorize! :manage, @post in the create, destroy, edit and update actions, for example, along with checking to make sure that the current_user.username == @post.username, can ensure that people can modify only their own posts.

Finally, instead of actually deleting posts, you may want users to instead "soft-delete" by simply marking a Post as deleted. In this case, you would explicitly authorize the creation and editing of Posts, but you would not authorize them to actually destroy Posts. In your index and show actions, you would ensure that Posts marked as deleted were not shown.

As to role-based systems, down the road you may want a group of moderators or to add on another administrator. That's when you'll want a role-based system. I almost always make mine role-based to start with, even if it's just to have admin and user roles.

platforms
  • 2,666
  • 1
  • 18
  • 23