Is it really needed to validate foreign keys?

自闭症网瘾萝莉.ら 提交于 2019-12-10 17:22:30

问题


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?


回答1:


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

validates_presence_of :article, :category

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.

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

belongs_to :article, :category


来源:https://stackoverflow.com/questions/13345250/is-it-really-needed-to-validate-foreign-keys

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!