Question from a newbie with Rails.
I have this:
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
in application_controller.rb
I have tried several ways to add to or to replace the exception message in a specific case such as
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
Here I use alert
and I have no alert message displayed. Trying notice
doesn't replace the exception message from the Cancan rescue.
I've also tried this:
<% 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 %>
in my show.html.erb page, which I find less dry than my code in the post_controller.rb above.
Before I try some nice code with css ot JS, I'd like to see at least something basic happening. Where does the problem come from ?
Of course, I have these lines in my pages:
<p class="notice"><%= notice %></p>
<p class="alert"><%= alert %></p>
Testing out on a new rails project, the following would make yours work:
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