cancan icon indicating copy to clipboard operation
cancan copied to clipboard

How do I check CanCan abilities in `shared/partial`?

Open marcamillion opened this issue 9 years ago • 0 comments

Per the 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?

marcamillion avatar Oct 18 '14 04:10 marcamillion