Saturday, 15 June 2013

ruby on rails - How can I enable admin to destroy the record when using CanCan? -



ruby on rails - How can I enable admin to destroy the record when using CanCan? -

my current code this. user posted can destroy own records. want enable admin(user.id=1) delete records.

how can alter this? view? smart way?

/models/ability.rb

def initialize(user) if user can :read, :all can [:create, :destroy], comment, {:user_id => user.id} can [:destroy], comment, {:commentable_id => user.id, :commentable_type => user.class.name} can [:create, :update], community, {:user_id => user.id} else can :read, :all end end

view

<%= link_to 'x', polymorphic_path([@user, comment]), :data => { :confirm => 'do want delete?' }, :method => :delete, :disable_with => 'deleting', :remote => true, :class => 'close' if current_user && current_user.id == comment.user_id || current_user && current_user.id == comment.commentable_id %>

here need. btw bad thought utilize user.id == 1 check admin rights, improve solution add together boolean admin field user model. if don't want it, can replace if user.admin? if user.id == 1.

def initialize(user) guest_ability user_ability(user) if user admin_ability if user.admin? # or `if user.id == 1` if don't want add together `admin` field end private def admin_ability(admin) can [:destroy], comment end def user_ability(user) can :read, :all can [:create, :destroy], comment, { :user_id => user.id } can [:destroy], comment, { :commentable_id => user.id, :commentable_type => user.class.name } can [:create, :update], community, { :user_id => user.id } end def guest_ability can :read, :all end

in view:

<% if can? :destroy, comment %> <%= link_to 'x', polymorphic_path([@user, comment]), :data => { :confirm => 'do want delete?' }, :method => :delete, :disable_with => 'deleting', :remote => true, :class => 'close' %> <% end %>

ruby-on-rails ruby-on-rails-3 ruby-on-rails-4 cancan

No comments:

Post a Comment