我正在尝试制作一个“更新和删除”按钮,该按钮仅在用户创建帖子或用户或版主 AND/OR 版主时才会显示。
我现在的posthelper是
def user_is_authorized_for_post?(post)
current_user && (current_user == post.user || current_user.admin?)
end
我的按钮是:
<% if user_is_authorized_for_post?(@post) %>
<%= link_to "Edit", edit_topic_post_path(@post.topic, @post), class: 'btn btn-success' %>
<%= link_to "Delete Post", [@post.topic, @post], method: :delete, class: 'btn btn-danger', data: { confirm: 'Are you sure you want to delete this post?' } %>
<% end %>
更新:我将 PostsHelper 更新为:
def user_is_authorized_for_post?(post)
current_user && (current_user == post.user || current_user.admin?) || (current_user == post.user || current_user.moderator?)
end
它有效,但我的问题是,是否有更好的编码方法,因为我觉得它太长了。
最佳答案
是的,有一种更短的写法。
您可以使用保护子句来缩短方法定义:
def user_is_authorized_for_post?(post)
return false unless current_user # the aforementioned guard clause
current_user == post.user || current_user.admin? || current_user.moderator?
end
关于ruby-on-rails - 显示和隐藏按钮的多种条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35002049/