3

One of the messier practices I have in Rails development is juggling validations of associated fields between validating the actual object (eg: validates_presence_of :related_object) and validating on the id column for that association (eg: validates_presence_of :related_object_id).

I figure I should probably start being a little more consistent with this, and before I commit to anything, I'm wondering if there's any advantage of either method over the other? I can't think of anything, but then I've been known to overlook stuff before. So, does it make any difference? Is there a convention re: what most developers do that I should abide by?

Any suggestions appreciated.

PlankTon
  • 12,443
  • 16
  • 84
  • 153

2 Answers2

1

Of course you have to check the presence of :object_id. If you check the presence of :object then this object will be fetched from your DB and then will be checked via simple blank?. I guess you won't be happy with additional DB hit.

jdoe
  • 15,665
  • 2
  • 46
  • 48
1

This question comes up every so often.

In most cases you will want to validate the presence of the actual associated object, not just verify that an id (which could well be invalid) has been set.

Validating association_id will also prevent you from creating the object with a new association record and saving both together.

Prathan Thananart
  • 4,007
  • 3
  • 19
  • 18