Rails 如何:如果项目有任务,则不应删除它:如何解决此问题?
您好,我有一个项目,每个项目都有任务。任务属于项目。在删除项目之前,我想检查是否有相关任务。如果有任务我不想删除该项目。如果没有关联的任务,则应删除该项目。你能帮我看一下代码吗?我缺少什么?
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
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
从 before_destroy 方法返回 false 以防止实例被销毁。
该方法还应该返回一个有意义的错误以进行故障排除。
注意:flash[:notice] 和 params[:attr_name] 只能在控制器中使用。
Return false from the before_destroy method to prevent the instance from being destroyed.
The method should also return a meaningful error for troubleshooting.
Note: flash[:notice] and params[:attr_name] can only be used from controllers.
你这里有几个问题。
params
变量(它仅在控制器和视图中可用,除非您将其传递给模型,这可能不是您想要的) 。if
检查project.tasks
这是一个数组 - 即使是空数组也会评估为true
,因此您的其他代码分支永远不会发生项目是否有任务无关紧要。解决方案:
Project.find(params[:id])
更改为self
- 您想要检查项目每个实例的任务。if
语句中的检查从if self.tasks
更改为if self.tasks.any?
,它会返回您想要的值 (false
如果数组为空,true
否则)。check_tasks
方法可以更改为以下代码:
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 againstproject.tasks
which is an array - even an empty array evaluates totrue
, so your other code branch will never occur no matter if the project has tasks or not.Solutions:
Project.find(params[:id])
toself
- you want to check the tasks for every instance of the Project.if
statement fromif self.tasks
toif 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:
支票应该是self吗? (不确定您从哪里获取 params[:id] )。
不过还没有检查过 - 但由于我的用户模型需要类似的东西,我会看看它是如何工作的并回复你。
Should the check be self instead? (not sure where you getting the params[:id] from).
Haven't checked this out yet though - but since I need something similar for my Users model I'll see how that works out and get back to you.