以 rails 形式验证多个模型 [英] validating multiple models in a rails form

查看:50
本文介绍了以 rails 形式验证多个模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读第 73 期的 railscast (http://railscasts.com/episodes/73-complex-forms-part-1),其中 Ryan Bates 解释了如何在单个表单中使用多个模型.他以单一形式创建了一个项目对象及其任务(一个简单的应用程序,您可以在其中创建一个项目及其相关任务)

I'm going through the railscast no 73 (http://railscasts.com/episodes/73-complex-forms-part-1), where Ryan Bates explains how to use multiple models in a single form. He creates a project object, along with its tasks, in a single form (A simple app, where you create a project and its associated tasks)

效果很好,但我不确定如何进行验证.正常验证(如存在等)很容易做到.但是,如何进行重复任务检查?如果我们添加validates_uniqueness_of,它将检查所有项目的所有任务,而我们只想检查正在创建的当前项目中的重复任务.

It works well, but I'm not sure how to do validation. The normal validations like presence etc is easy to do. But, how to do duplicate task check? If we add validates_uniqueness_of, it will check against all tasks of all projects, whereas we would want to check for duplicate tasks only in the current project that is being created.

推荐答案

你想做的是:

validates_uniqueness_of :task_name, :scope => :project_id

这篇关于以 rails 形式验证多个模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆