2

I am using pundit to handle authorizations in a ruby on rails app and I want to see if the user who is logged in can moderate before showing delete and edit buttons for posts, comments, etc.

Here's the original working method in post policy, comment policy etc

 def destroy
   user.present? && (user == record.user || user.role?(:admin) || user.role?(:moderator))
 end

Here's the new method I added to application policy

  def can_moderate?(user, record)
    @user = user
    @record = record
    user == record.user || user.role?(:admin) || user.role?(:moderator)
  end

Here's the DRYer post policy I'm working on

  def destroy?
    user.present? && user.can_moderate?
  end

This DRYer version gives me an undefined error method for can_moderate. Any thoughts on why?

Thanks!

EDIT TO ADD FULL ERROR

ActionView::Template::Error (undefined method `can_moderate?' for #<User:0xb5671e60>):
14:     <% if policy(@post).edit? %>
15:       <%= link_to "Edit", edit_topic_post_path(@topic, @post), class: 'btn btn-success' %>
16:     <% end %>
17:     <% if policy(@post).destroy? %>
18:       <%= link_to "Delete", [@topic, @post], method: :delete, class: 'btn btn-danger', data: { confirm: 'Are you sure you want to delete this topic?' } %>
19:     <% end %>
20:   </div>
app/policies/post_policy.rb:7:in `destroy?'
app/views/posts/show.html.erb:17:in `_app_views_posts_show_html_erb___159039275__620331048'
4

2 回答 2

2

Tien,

Do not call the can_moderate? on the user object. It would assume the can_moderate? is present in the user class/model. Instead just call the method since in the present in same file/controller.

  def destroy?
    user.present? && can_moderate?
  end

Also you can have your can_moderate? method to just

  def can_moderate?(user, record)
    user == record.user || user.role?(:admin) || user.role?(:moderator)
  end
于 2014-09-20T19:59:23.927 回答
-1

DRYer version,

# policy file
def destroy?
  can_moderate?
end

def can_moderate?(user, record)
  user.present? && user == record.user ||
                   user.role?(:admin)  || user.role?(:moderator)
end
于 2016-12-02T14:05:14.227 回答