Ruby On Rails Rolify + CanCanCan + Devise allow user to edit only their posts -


i have built ruby on rails application using devise + cancancan + rolify tutorial.

here ability model:

class ability   include cancan::ability    def initialize(user)     user ||= user.new # guest user (not logged in)     if user.has_role? :admin       can :manage, :all     else       can :read, :all     end   end end 

i want allow user edit own posts, , read posts others.

how achieve that?

you need pass user_id hash conditions:

#app/models/ability.rb class ability   include cancan::ability    def initialize(user)     user ||= user.new # guest user (not logged in)     if user.has_role? :admin       can :manage, :all     else       can :manage, post, user_id: user.id #-> crud own posts       can :read, :all #-> read     end   end end 

this allow use:

#app/views/posts/index.html.erb <%= render @posts %>  #app/views/posts/_post.html.erb <% if can? :read, post %>    <%= post.body %>    <%= link_to "edit", edit_post_path(post), if can? :edit, post %> <% end %> 

Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

javascript - Get parameter of GET request -

javascript - Twitter Bootstrap - how to add some more margin between tooltip popup and element -