Module: Controllers::Destroyable

Instance Method Summary collapse

Instance Method Details

#destroyObject



6
7
8
# File 'app/concerns/controllers/destroyable.rb', line 6

def destroy
  perform_destroy controller_name.classify.constantize, params[:destroy]
end

#perform_destroy(record_class, options = nil) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'app/concerns/controllers/destroyable.rb', line 10

def perform_destroy(record_class, options = nil)
  options ||= {}
  @error_msg = []
  record_identifier = "#{record_class.name.titleize} record id #{params[:id]}"
  record_instance_name = "@#{record_class.name.tableize.singularize}"
  begin
    record = instance_variable_get(record_instance_name) || record_class.find(params[:id])
    authorize! :destroy, record
    record.destroy
    @error_msg += record.errors.full_messages
    instance_variable_set(record_instance_name, record)
  rescue ActiveRecord::RecordNotFound
    @error_msg << "#{record_identifier} not found."
  rescue CanCan::AccessDenied
    @error_msg << "Insufficient permissions to destroy #{record_identifier}"
  end
  if @error_msg.empty?
    flash[:info] = "#{record_identifier} was deleted successfully."
    redir_url = options[:success_url]
  else
    flash[:error] = "#{record_identifier} could not be deleted. #{@error_msg.join(',')}"
    redir_url = options[:error_url]
  end
  redir_url ||= options[:redir_url]
  redir_url ||= url_for(action: :index)
  # Redirection will be either succes/error url, or a generalized redir url option, or the index action
  redirect_to_return_path_or_default redir_url
end