4

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?

Community
  • 1
  • 1
user12882
  • 4,702
  • 9
  • 39
  • 54
  • 1
    An association only makes sense when it describes an existing article and category. You need these constraints to keep your database consistent. What's the point of associating an article with "nothing"? – toniedzwiedz Nov 12 '12 at 14:29
  • @Tom - Should I state validation methods *explicitly* (as I made in the question)? – user12882 Nov 12 '12 at 15:25

1 Answers1

3

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
Andrew
  • 42,517
  • 51
  • 181
  • 281
  • Doesn't that add some serious overhead to the app? Wouldn't it be better to add constraints at the db level? – dee Jun 14 '13 at 20:20
  • That depends on your app and how you define serious overhead. If this is user-facing and users are CRUD'ing a few records at a time, this is not going to add a measurable impact. If you're doing something as an admin with a million records at a time, it may be meaningful overhead. But, if you're doing something as an admin with a million records at a time, you probably shouldn't be doing it in the application code in the first place. – Andrew Jun 16 '13 at 00:53