问题
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