【发布时间】:2018-03-23 13:22:29
【问题描述】:
来自 Rails 新手的问题。
我有这个:
rescue_from CanCan::AccessDenied do |exception|
respond_to do |format|
format.json { head :forbidden, content_type: 'text/html' }
format.html { redirect_to main_app.root_url, notice: exception.message }
format.js { head :forbidden, content_type: 'text/html' }
end
end
在 application_controller.rb 中
我尝试了几种方法来添加或替换特定情况下的异常消息,例如
def show
authorize! :read, @post, :alert => "Please log in to access this page"
@post = Post.find(params[:id])
@posts = Post.order("created_at DESC").limit(4).offset(1)
end
我在这里使用alert,但没有显示任何警报消息。尝试notice 并不能替换来自 Cancan 救援的异常消息。
我也试过这个:
<% if user_signed_in? %>
<% if can? :update, @post %>
<p><%= link_to "modify", edit_post_path(@post.id) %></p>
<% else %>
<%= flash[:alert] = 'Please log in to access this page' %>
<% end %>
<% end %>
在我的 show.html.erb 页面中,我发现它比上面 post_controller.rb 中的代码干的少。
在我尝试使用 css ot JS 编写一些不错的代码之前,我希望至少看到一些基本的事情发生。问题出在哪里?
当然,我的页面中有这些行:
<p class="notice"><%= notice %></p>
<p class="alert"><%= alert %></p>
【问题讨论】:
-
哦,看来您实际上可以将
message:从HERE 传入authorize! -
这就是我看到可能性的地方,它看起来不错,但不适用于我。
-
您是否尝试将
:message传递给authorize!?不支持:alert。 -
之后,这应该已经可以工作了,因为
exception.message正在以:notice的形式传递到您的redirect_to main_app.root_url,并且您的页面中已经有<%= notice %>。如果这仍然不起作用,您可能在某处覆盖了flash[:notice]的值。 -
为了确保消息已经被传递到重定向中,尝试通过在
rescue_from CanCan::AccessDenied do |exception|正下方插入puts exception.message来进行调试
标签: ruby-on-rails ruby-on-rails-5 cancancan