【问题标题】:cancancan alert and notice messagescancancan 警报和通知消息
【发布时间】: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,并且您的页面中已经有&lt;%= notice %&gt;。如果这仍然不起作用,您可能在某处覆盖了 flash[:notice] 的值。
  • 为了确保消息已经被传递到重定向中,尝试通过在 rescue_from CanCan::AccessDenied do |exception| 正下方插入 puts exception.message 来进行调试

标签: ruby-on-rails ruby-on-rails-5 cancancan


【解决方案1】:

在一个新的 Rails 项目上进行测试,以下内容将使您的工作正常:

app/controllers/SOMECONTROLLER.rb

def show
  authorize! :show, @post, message: 'Please log in to access this page'
  # and not...
  # authorize! @post, message: 'Please log in to access this page'
  # ...
end

【讨论】:

  • 您的意思是在 application_helper 中添加 add_flash_types 之后?目前,我有一个路由错误。
  • 我没有将add_flash_types 添加到application_helper.rb 中。什么是路由错误?我猜您已获得授权,因此它跳过了上面的那一行,因此错误可能来自这一行? @post = Post.find(params[:id])?如果不是,你能显示路由错误是什么吗?
  • 你也可以再试一次吗:为了确保消息已经被传递到重定向,尝试通过在rescue_from CanCan::AccessDenied do |exception|正下方插入 puts exception.message 来调试
  • 我在 application_helper.rb 中正确定义了 flash_type 'message' 后,路由错误消失了,但最终结果是一样的。你是对的:调试显示了预期的消息。我只需要为它添加html。非常感谢!
  • 哦,您添加了一个名为:message 的自定义闪存类型?那是因为你在某处有一个flash[:message]。除非您真的打算这样做,否则您实际上并不需要自定义 Flash 消息。只有两种默认 flash 类型::notice:alert
猜你喜欢
  • 2017-03-15
  • 1970-01-01
  • 1970-01-01
  • 2013-09-19
  • 1970-01-01
  • 2017-01-19
  • 1970-01-01
  • 2018-05-07
  • 2013-07-18
相关资源
最近更新 更多