Ruby on rails 如果文章是他们自己的,如何允许用户只查看编辑和删除链接?
我的用户是通过Desive建立的。我也可以用CanCanCan 我建立了一个文章模型,任何用户都可以创建文章。他们只能删除和编辑自己的文章创作。在索引上,他们可以查看所有用户创建的所有文章。当前有一个查看、编辑和删除选项。我只希望该选项在用户拥有的文章上可见。我希望所有其他文章行为空。(当然除了管理员。) 用户可以在views/articles/index.html.erb上查看帖子Ruby on rails 如果文章是他们自己的,如何允许用户只查看编辑和删除链接?,ruby-on-rails,devise,cancan,Ruby On Rails,Devise,Cancan,我的用户是通过Desive建立的。我也可以用CanCanCan 我建立了一个文章模型,任何用户都可以创建文章。他们只能删除和编辑自己的文章创作。在索引上,他们可以查看所有用户创建的所有文章。当前有一个查看、编辑和删除选项。我只希望该选项在用户拥有的文章上可见。我希望所有其他文章行为空。(当然除了管理员。) 用户可以在views/articles/index.html.erb上查看帖子 <table> <tr> <th>Title</th>
<table>
<tr>
<th>Title</th>
<th>Description</th>
</tr>
<% @articles.each do |article| %>
<tr>
<td><%= article.title %></td>
<td><%= article.description %></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 %>
</table>
由于您可以访问Desive提供的
当前用户
帮助程序,因此您可以将其与文章的所有者进行比较。这可以在视图中显示,以呈现适当的链接以执行操作:
<% @articles.each do |article| %>
<tr>
<td><%= article.title %></td>
<td><%= article.description %></td>
<td><%= link_to 'View', article_path(article) %></td>
<% if current_user == article.user %>
<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 %>
传递对象,这将返回true或false,具体取决于当前用户是否等于对象
用户。该视图仅更改为:
<% if owner?(article) %>
如果您想在回调之前将此部分移动到,以便能够在编辑和销毁方法中使用它,那么您可以将其添加为私有方法,并且可以访问@文章
,您可以进行这样的比较:
private
def owner?
unless current_user == @article.user
redirect_back fallback_location: root_path, notice: 'User is not owner'
end
end
这样,您只需在执行操作之前将其添加为回调:
before_action :owner?, only: %i[edit destroy]
很可能在定义@article变量之前
注意在Rails 5中使用了redirect\u back
,以前的版本可能会使用redirect\u to:back
谢谢您的帮助。我目前不在电脑旁,但过一会儿会试试这个。
module ApplicationHelper
def owner?(object)
current_user == object.user
end
end
<% if owner?(article) %>
def edit
unless current_user == @article.user
redirect_back fallback_location: root_path, notice: 'User is not owner'
end
end
private
def owner?
unless current_user == @article.user
redirect_back fallback_location: root_path, notice: 'User is not owner'
end
end
before_action :owner?, only: %i[edit destroy]