2014-10-06 76 views
0

这是我的代码,用于我的index.html.erb脚手架 ,因为您可以看到if else会阻止用户“显示,编辑或销毁” 条目。但是,他们可以通过单击新建 Rotum来创建新的Rota条目。我可以摆脱管理部分显示,编辑,销毁和大家将能够做的一切。但我想要一个用户能够 只显示编辑摧毁他们自己的条目,并不是每个人都太 因为这是什么时,我认证用户做到这一点?Devise gem用户身份验证Ruby on Rails

<h1>Listing rota</h1> 

<table id = "tabletest"> 
    <thead> 
    <tr> 
    <th>Name</th> 
    <th>Mobile</th> 
    <th>Email</th> 
    <th>Category</th> 
    <th>Other</th> 
    <th colspan="3"></th> 
    </tr> 
</thead> 

<tbody> 
    <% @rota.each do |rotum| %> 
    <tr> 
    <td><%= rotum.name %></td> 
    <td><%= rotum.mobile %></td> 
    <td><%= rotum.email %></td> 
    <td><%= rotum.category %></td> 
    <td><%= rotum.other %></td> 

<% if current_user.try(:admin?) %> 
    <td><%= link_to 'Show', rotum %></td> 
    <td><%= link_to 'Edit', edit_rotum_path(rotum) %></td> 
    <td><%= link_to 'Destroy', rotum, method: :delete, data: { 
    confirm: 'Are you sure?' } %></td> 
    </tr> 
    <% end %> 
     <% end %> 
</tbody> 
</table> 

<br> 
    <% if user_session %> 
<%= link_to 'New Rotum', new_rotum_path %> 
    <% end %> 

回答

0

假设userrota之间的关系是一个has_many,您的索引控制器应该是:

class RotasController < ApplicationController 
    def index 
    @rota = current_user.rotas 
    end 
end 

current_user是由设计规定的辅助方法,如图here

0

情况1: 如果您想要显示用户在表格中创建的轮回。

class RotasController < ApplicationController 
    def index 
    @rota = Rota.where(current_user.try(:admin?) ? true : {user_id: current_user.id}) 
    end 
end 

这将获取所有的记录管理,如果用户不是管理员,将取回相关记录。

并在视图文件

<tbody> 
    <% @rota.each do |rotum| %> 
    <tr> 
    <td><%= rotum.name %></td> 
    <td><%= rotum.mobile %></td> 
    <td><%= rotum.email %></td> 
    <td><%= rotum.category %></td> 
    <td><%= rotum.other %></td> 

    <td><%= link_to 'Show', rotum %></td> 
    <td><%= link_to 'Edit', edit_rotum_path(rotum) %></td> 
    <td><%= link_to 'Destroy', rotum, method: :delete, data: { 
    confirm: 'Are you sure?' } %></td> 
    </tr> 
<% end %> 

案例2: 在另一种情况下,如果要显示所有记录每一个用户,但用户可以访问“节目,编辑,删除',只有当他创建了那个..然后你需要做别的事情。

class RotasController < ApplicationController 
    def index 
    @rota = Rota.all 
    @is_admin = current_user.try(:admin?) 
    end 
end 

并在视图

<tbody> 
    <% @rota.each do |rotum| %> 
    <tr> 
    <td><%= rotum.name %></td> 
    <td><%= rotum.mobile %></td> 
    <td><%= rotum.email %></td> 
    <td><%= rotum.category %></td> 
    <td><%= rotum.other %></td> 
    <% if @is_admin || (rotum.user_id == current_user.id) 
     <td><%= link_to 'Show', rotum %></td> 
     <td><%= link_to 'Edit', edit_rotum_path(rotum) %></td> 
     <td><%= link_to 'Destroy', rotum, method: :delete, data: { 
    confirm: 'Are you sure?' } %></td> 
    <% else %> 
     <td colspan='3'> &nbsp; </td> 
    <% end %> 
    </tr> 
<% end %> 

希望,它会为你工作。 :)

+0

我尝试这样做,管理员可以做的一切,但是当用户迹象,它说,“对于在# NoMethodError /罗塔 未定义的方法'user_ID的” ” – Rahid 2014-10-09 12:57:00