Like Rails: if a project has tasks, it cannot be deleted: how can I fix it?

Hi, I have a project and every project has tasks. The task belongs to the project. Before deleting a project, I want to check if there are any related tasks. If there are tasks, I do not want to delete the project. If there are no related tasks, the project should be deleted. Could you help me with the code? What am I missing?

class Project < ActiveRecord::Base  
  before_destroy :check_tasks    

  def check_tasks 
    if Project.find(params[:id]).tasks  
      flash[:notice] = 'This project has tasks.'
      redirect_to :action => 'list_projects'    
    end 
  end
end
+5
source share
3 answers

Returns false from the before_destroy method to prevent the destruction of the instance.

The method should also return a meaningful error for troubleshooting.

class Project < ActiveRecord::Base
  before_destroy :check_tasks

  def check_tasks
    if self.tasks.any?
      errors.add_to_base "Project has tasks and cannot be destroyed."
      return false
    end
  end
end

Note: flash [: notice] and params [: attr_name] can only be used from controllers.

+6

.

  • ( ) params ( , , , , , ).
  • if project.tasks, - true, , .
  • , ProjectController #, .

:

  • Project.find(params[:id]) self - .
  • if if self.tasks if self.tasks.any?, (false, , true ).
  • [: ] , redirect_to, . , check_tasks :

:

def check_tasks
  return !self.tasks.any?
end
+2

self ? ( , [: id] from).

, , - , , .

class Project < ActiveRecord::Base  
 before_destroy :check_tasks

 private

 def check_tasks
   #edited 
   if tasks.empty?  
     false
   end 
 end
+1

All Articles