【发布时间】:2017-10-08 16:54:58
【问题描述】:
我的用户是通过 Devise 设置的。我也可以使用 CanCanCan。
我设置了一个文章模型,任何用户都可以创建文章。他们只能删除和编辑自己的文章创作。在索引上,他们可以查看所有用户创建的所有文章。当前有一个查看、编辑和删除的选项。我只希望该选项在用户拥有的文章上可见。我希望所有其他文章行都是空白的。 (当然管理员除外。) 用户可以在views/articles/index.html.erb上查看帖子
<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>
我怎样才能让用户只看到他们拥有的帖子上的编辑和删除按钮?
我试过了,但它不起作用:
<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>
<% if user_signed_in? && current_user.articles.exists?(@article.id) %>
<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>
我也试过了:
<% if current_user && current_user.articles.exists?(@article.id) %>
这是我的文章控制器的外观:(我知道我需要让它看起来更好。)
def create
@article = current_user.articles.build(article_params)
if @article.save
redirect_to @article
else
render 'new'
end
end
def update
@article = Article.find(params[:id])
if user_signed_in? && current_user.articles.exists?(@article.id)
if @article.update(article_params)
redirect_to @article
else
render 'edit'
end
elsif current_user && current_user.admin_role?
if @article.update(article_params)
redirect_to @article
else
render 'edit'
end
else
redirect_to @article
end
end
def destroy
@article = Article.find(params[:id])
if user_signed_in? && current_user.articles.exists?(@article.id)
@article.destroy
redirect_to articles_path
elsif current_user && current_user.admin_role?
@article.destroy
redirect_to articles_path
else
redirect_to articles_path
end
end
【问题讨论】:
标签: ruby-on-rails devise cancan