簡體   English   中英

在Ruby on Rails的index.html.erb上實現cancancan的最干凈方法是什么?

[英]What is the cleanest way of implementing cancancan on my index.html.erb in Ruby on Rails?

我只是想知道每個人建議在他們的.html頁面中使用cancan的建議嗎?

關於我當前設置的一些信息...我的/app/models/ability.rb:

 user ||= User.new # guest user (not logged in)
 if user.admin?
   can :manage, :all
 else
   can :read, :all
 end

我正在使用articles_controller.rb,並建立了一個文章模型。

我在我的article_controller.rb中使用load_and_authorize_resource方法

因此,進入我的index.html.erb。

我的頁面上有一些CRUD選項,我只希望某些鏈接和選項(例如編輯和刪除)對管理員用戶可見。

在index.html.erb的一部分中,我具有此鏈接,該鏈接只能由管理員查看。

<% if can? :create, @article %>
<%= link_to 'Post New Load Data!', new_article_path %>
<% end %>

^這對我想要的是完美的。

但是我的index.html上還有另一個區域令我感到困惑。 像這樣...

<% if current_user && current_user.admin? %>
<table>
 <tr>
    <th>Title</th>
  </tr>

  <% @articles.each do |article| %>
   <tr>
     <td><%= article.title %></td>
     <td><%= link_to 'View', article_path(article) %> |</td>
     <td><%= link_to 'Edit', edit_article_path(article) %> |</td>
     <td><%= link_to 'Delete', article_path(article),
             method: :delete,
             data: { confirm: 'Are you sure?' } %></td>
   </tr>
  <% end %>
<p>
</table>
<% else %>
<table>
 <tr>
    <th>Title</th>
  </tr>
  <% @articles.each do |article| %>
   <tr>
     <td><%= article.title %></td>
     <td><%= link_to 'View', article_path(article) %> |</td>
   </tr>
  <% end %>
  </table>
  <% end %>

因此,它允許管理員查看“編輯”和“刪除”選項。 這就是我想要的,但是我沒有使用CanCan來做到這一點。 有沒有一種方法可以使用CanCan簡化此過程? 這樣,我不必重復很多部分。

我喜歡堅持使用devise的current_user.admin嗎? 因為它讀起來很漂亮:

<table>
 <tr>
  <th>Title</th>
 </tr>

 <% @articles.each do |article| %>
  <tr>
   <td><%= article.title %></td>
   <td><%= link_to 'View', article_path(article) %> |</td>
   <% if current_user.admin? %>
    <td><%= link_to 'Edit', edit_article_path(article) %> |</td>
    <td><%= link_to 'Delete', article_path(article),
            method: :delete,
            data: { confirm: 'Are you sure?' } %></td>
   <% end %>
  </tr>
 <% end %>
</table>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM