难道真的需要验证外键? [英] Is it really needed to validate foreign keys?

查看:175
本文介绍了难道真的需要验证外键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用on Rails的V3.2.2 Ruby和,张贴后,我的<一个href="http://stackoverflow.com/questions/13344059/trouble-with-foreign-key-validations-when-using-accepts-nested-attributes-for">$p$pvious问题,我想知道,如果(或没有)理解到的明确的验证与 ActiveRecord的外键::协会是必要的。例如:

I am using Ruby on Rails v3.2.2 and, after post my previous question, I would like to know and understand if (or not) to explicitly validate foreign keys related to ActiveRecord::Associations is needed. For example:

class CategoryAssociation < ActiveRecord::Base
  belongs_to :article, :foreign_key => 'article_id'
  belongs_to :category, :foreign_key => 'category_id'

  validates :article_id, :presence => true, :numericality => { :only_integer => true }
  validates :category_id, :presence => true, :numericality => { :only_integer => true }
end

在上面验证方法的真正的需要?为什么呢?

Are above validates methods really needed? Why?

推荐答案

我不会做你正在做的方式,但我会做到:

I would not do it the way you're doing it, but I would do:

validates_presence_of :article, :category

我不知道它的绝对必要的,但这种prevents你能够只保存了部分关联。这将是很难建立在正常的轨道使用的部分关联,但这样一来就不会发生了。

I'm not sure its absolutely necessary, but this prevents you from being able to save only a partial association. It would be hard to create a partial association in normal rails usage, but this way it would not happen.

另外,你不需要 foreign_key 在任何一个社团,只是

Also, you don't need foreign_key on either of those associations, just

belongs_to :article, :category

这篇关于难道真的需要验证外键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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