来自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或JS的一些不错的代码之前,我希望至少看到一些基本的事情发生。问题出在哪里?
当然,我的网页上有这些内容:
<p class="notice"><%= notice %></p>
<p class="alert"><%= alert %></p>
答案 0 :(得分:1)
测试新的rails项目,以下内容将使您的工作:
应用/控制器/ 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