Answer the question
In order to leave comments, you need to log in
Why does Devise or Cancan logout the admin when trying to delete any entry?
Hello.
Maybe someone came across. When I click on the link in the browser to delete any resource, such as a category, I am logged out and redirected to the login page. Both cancan and devise (depending on how I check in the controller). The rest of the actions work.
The code has the following:
app/models/ability.rb
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new # guest user (not logged in)
if user.has_role? :admin
can :manage, :all
end
end
end
class Admin::CategoriesController < ApplicationController
layout "admin"
# метод cancan
load_and_authorize_resource
# в другом контроллере вместо load_and_authorize_resource используется devise'овский метод:
before_filter :authenticate_user! # для эксперимента
# ...
# весь код после скаффолда даже не изменялся
# ...
# DELETE /admin/categories/1
# DELETE /admin/categories/1.json
def destroy
@category = Category.find(params[:id])
@category.destroy
respond_to do |format|
format.html { redirect_to admin_categories_url }
format.json { head :no_content }
end
end
class Category < ActiveRecord::Base
has_many :subcategories, class_name: "Category"
belongs_to :parent_category, class_name: "Category", foreign_key: "category_id"
attr_accessible :name, :description, :category_id, :order
validates_presence_of :name
before_create :set_max_order
after_initialize :set_max_order, :if => Proc.new { |c| self.order < 1 }
private
def set_max_order
self.order = max_order + 1
end
def max_order
Category.maximum(:order) || 0
end
end
<% @categories.each do |category| %>
# ....
<% if can? :destroy, category %>
<td><%= link_to 'Delete', category, confirm: 'Are you sure?', method: :delete %></td>
<% end %>
<% end %>
it "should delete category" do
visit admin_categories_path
expect { click_link "Delete" }.to change(Category, :count).by(-1)
end
it "should definately delete category" do
visit admin_categories_path
page.should have_selector('table.data tbody tr', :count => 1)
click_link "Delete"
page.should_not have_selector('table.data tbody tr')
page.should have_content('Categories')
end
Request URL: /admin/categories/5
Request Method: POST
Status Code: 302 Found
Answer the question
In order to leave comments, you need to log in
<%= csrf_meta_tag %> was not forgotten in the template, by any chance?
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question