Hi I have a project and each project has tasks. A task belongs to a project. Before I delete a project I want to check if there are related tasks. If there are tasks I don't want to delete the project. If there are no associated tasks, the project should be deleted. Can you please 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
Return false from the before_destroy method to prevent the instance from being destroyed.
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.
You have a couple of problems here.
params
variable (it's available in controllers and views only, unless you're passing it to the model, which is probably not what you want).if
checks against project.tasks
which is an array - even an empty array evaluates to true
, so your other code branch will never occur no matter if the project has tasks or not. Solutions:
Project.find(params[:id])
to self
- you want to check the tasks for every instance of the Project.if
statement from if self.tasks
to if self.tasks.any?
which returns the value you want (false
if the array is empty, true
otherwise).check_tasks
method can be changed to the following:code:
def check_tasks
return !self.tasks.any?
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With