Search code examples
ruby-on-railscancancancancan

cancancan auth in the view


Im adding in cancancan to my app for authorisation, and ive can across a snag.

I have a voting system where as you cant vote on your on own entry but you can edit, delete etc.

So ive created a block inside the ability class.

def initialize(user)
  if user.present?
    if user.admin?
      can :manage, :all

    else
      can :vote, Entry do |entry|
        user.id != entry.user_id
      end
      can :manage, Entry, user_id: user.id
      can :manage, Message, user_id: user.id
      can :manage, Profile, user_id: user.id
      can :manage, User, user_id: user.id

    end

   can :read, :all

  end
 end

here is where im calling the can? method:

<% @entries.each do |x| %>

 <% if can? :vote, x %>
  <span class="text-green"> <%= link_to like_entry_path(x), method: :put, remote: true do %>
    <i class="fas fa-chevron-up"></i>
  <% end %>
  </span>
  <span class="badge" id="upvote-count<%=x.id%>"><%= x.get_upvotes.size%></span>
  <span class="text-red"> <%= link_to unlike_entry_path(x), method: :put, remote: true do %>
    <i class="fas fa-chevron-down"></i>
  <% end %>
  </span>
  <span class="badge" id="downvote-count<%=x.id%>"><%= x.get_downvotes.size%></span>
 <% else %>
  <i class="fas fa-chevron-up text-grey"></i>
  <span class="badge"><%= x.get_upvotes.size%></span>
  <i class="fas fa-chevron-down text-grey"></i>
  <span class="badge"><%= x.get_downvotes.size%></span>
 <% end %>
<% end %>

But its still printing the links when it shouldn't?

When debugging, On the first entry i check user.id != entry.user_id and its comes back as false, so i can vote on it, but in the second loop that same query comes back as true as it should do but the links still appear in the view?

To sum it up if that was a bit confusing, Two entries made to two different accounts but the voting links appear on both entries.


Solution

  • Define the ability like this:

    cannot :vote, Entry if  user_id: user.id 
    

    Doc: Defining-Abilities-with-Blocks#only-for-object-attributes