验证 has_many/belongs_to 关系
我有一个食谱模型,其中有很多成分(又属于食谱)。我希望成分的存在依赖于配方;如果没有配方,成分就不应该存在。
我正在尝试强制成分中存在有效的配方 ID。我一直在使用 validates :recipe, :presence => 来做到这一点Ingredient 中的 true
(Rails 3) 语句。如果我在将成分添加到其 ingredients
集合之前保存配方,则效果很好。但是,如果我没有对保存的明确控制(例如当我从嵌套表单创建食谱及其成分时),则会收到错误消息:
食材配方不能为空
我可以通过删除 Ingredient.recipe 上的存在验证来解决这个问题。然而,我不太喜欢这样,因为这意味着我在没有安全网的情况下工作。
在 Rails 中强制执行存在依赖性的最佳方法是什么?
我正在考虑的事情(请评论每件事的智慧):
- 在配料.recipe_id 数据库列上添加非空约束,并让数据库为我进行检查。
- 自定义验证,以某种方式检查成分是否在未保存的配方的成分集合中(因此不能有recipe_id,但仍然被认为是有效的)。
I have a Recipe model which has_many Ingredients (which in turn belongs_to Recipe). I want Ingredient to be existent dependent on Recipe; an Ingredient should never exist without a Recipe.
I'm trying to enforce the presence of a valid Recipe ID in the Ingredient. I've been doing this with a validates :recipe, :presence => true
(Rails 3) statement in Ingredient. This works fine if I save the Recipe before adding an Ingredient to it's ingredients
collection. However, if I don't have explicit control over the saving (such as when I'm creating a Recipe and its Ingredients from a nested form) then I get an error:
Ingredients recipe can't be blank
I can get around this simply by dropping the presence validation on Ingredient.recipe. However, I don't particularly like this, as it means I'm working without a safety net.
What is the best way to enforce existence-dependence in Rails?
Things I'm considering (please comment on the wisdom of each):
- Adding a not-null constraint on the ingredients.recipe_id database column, and letting the database do the checking for me.
- A custom validation that somehow checks whether the Ingredient is in an unsaved recipe's ingredient collection (and thus can't have a recipe_id but is still considered valid).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
看看这个:
https://rails.lighthouseapp.com/projects/8994/tickets/2815-nested-models-build-should-directly-assign-the-parent
过去我想我添加了一个:上 => :验证器的更新选项,有助于稍微收紧网络。我认为数据库中的外键限制是个好主意,尽管我很少使用它:(
Take a look at this:
https://rails.lighthouseapp.com/projects/8994/tickets/2815-nested-models-build-should-directly-assign-the-parent
In the past I think I've added a :on => :update option to the validator, helps tighten the net a little. I think the foreign key restriction in the DB is a good idea, although I rarely use it : (