marcamillion
marcamillion

Reputation: 33785

How do I check CanCan abilities on an object in a `shared/partial`?

Per the CanCan documentation, to check if a user has the ability to do something to any element in the view, you do something like this:

<% if can? :create, @project %>
  <%= link_to "New Project", new_project_path %>
<% end %>

Or you can check with the class like:

<% if can? :create, Project %>
  <%= link_to "New Project", new_project_path %>
<% end %>

In my case, I have a DashboardController#Index, that has this:

@nodes = current_user.nodes.where(:is_comment => nil) 

In my views/dashboard/index.html.erb, I have this:

      <% @nodes.each do |node| %>
            <!-- Upload Video Comment Popup -->
      <div class="box">
          <%= render partial: "shared/comments", locals: {node: node} %>
      </div>
      <% end %> <!-- node -->

Then in my shared/_comments.html.erb, I have this:

       <% if node.comments.present? %>
          <% node.comments.each do |comment| %>
             <% if can? :manage, Comment %> 
                Show Something Interesting Here                                                                 
             <% else %>
                 Show something boring here
              <% end %>                                                                 
           <% end %>
        <% end %>

That doesn't work.

I also tried this:

       <% if node.comments.present? %>
          <% node.comments.each do |comment| %>
             <% if can? :manage, comment %> 
                Show Something Interesting Here                                                                 
             <% else %>
                 Show something boring here
              <% end %>                                                                 
           <% end %>
        <% end %>

And that doesn't work either.

This is my ability.rb

can :manage, Comment, user_id: user.id

I thought about creating a @comments instance variable in the controller, but the issue with that is that the comments are on a collection of nodes (i.e. I need to show multiple nodes, and each node has multiple comments).

How do I approach this?

Upvotes: 1

Views: 395

Answers (1)

AnatoliiD
AnatoliiD

Reputation: 471

Your last code should work after updating to CanCanCommunity version of cancan

<% if node.comments.present? %>
  <% node.comments.each do |comment| %>
     <% if can? :manage, comment %>
        Show Something Interesting Here
     <% else %>
         Show something boring here
      <% end %>
   <% end %>
<% end %>

related to How do I show an error for unauthorized can can access

Upvotes: 1

Related Questions