2014-10-18 54 views
1

%的CanCan文檔,以檢查用戶是否有做一些事情中的任何元素的觀點的能力,你做這樣的事情:如何在「共享/部分」對象中檢查CanCan能力?

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

或者你可以用類象檢查:

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

就我而言,我有一個DashboardController#Index,具有此:

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

在我views/dashboard/index.html.erb,我有這樣的:

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

然後在我shared/_comments.html.erb,我有這樣的:

 <% 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 %> 

這是行不通的。

我也試過這樣:

 <% 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 %> 

這也不行。

這是我ability.rb

can :manage, Comment, user_id: user.id 

我想到了創建一個控制器中的@comments實例變量,但這個問題是,comments上節點的集合(即我需要顯示多個節點,並且每個節點都有多個註釋)。

我該如何解決這個問題?

回答

1

你最後的代碼應該更新到的康康舞

<% 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 %> 

相關CanCanCommunity版How do I show an error for unauthorized can can access

+0

真棒花花公子後工作。你今天一直在滾動! – marcamillion 2014-10-18 23:57:32