Rtt
Rtt

Reputation: 21

Each user can see only records what created himself

I'm using rails_admin and devise for authentication. How can I make to every user can manage only the records in post model what created himself? I think I need to use cancan, but i don't kwoh how.

Upvotes: 0

Views: 154

Answers (2)

Richard Peck
Richard Peck

Reputation: 76774

Your right in your assumption of having to use CanCan. Reason being you're looking at authorization

The difference between Authentication & Authorization is the former defines whether someone can access the system or not; whilst the latter will define whether an authenticated user will be able to access / change a particular resource

The CanCan gem was created by Ryan Bates to give users access to specific records. As Danny as pointed out, you'll need to do something like this:


Associate a post with a user - use something like:

#app/models/post.rb
Class Post < ActiveRecord::Base
   belongs_to :user #-> means you need user_id column in posts table
end

#app/models/user.rb
Class User < ActiveRecord::Base
   has_many :posts
end

Then you'll be able to use a gem like CanCan to provide authorization:

#app/models/ability.rb
class Ability
  include CanCan::Ability

  def initialize(user)
     can :edit, Post, user_id: user.id 
  end

end  

#app/views/posts/index.html.erb
<% for post in @posts do %>
   <% if can? :edit, post %>
       <%= post.title %>
   <% end %>
<% end %>

Upvotes: 0

Danny
Danny

Reputation: 6025

Two steps:

  1. store the current user in the Post model as 'user_id' at creation

  2. using CanCan, put in ability.rb

    can :manage, Post, :user_id => user.id

This way, each user can manage only those Posts for which he was stored as creator

Upvotes: 1

Related Questions