Monday, September 26, 2011

Rails 3 - Check if any possibilities exist before validation

In this work project I have a few models: contest model, submission model, and subject model. Subject is a table that belongs to contest, AND subject. Some contests don't have subjects, but if they do, I need to have the user select one. These few snips of code worked well for that situation:

class Submission < ActiveRecord::Base
  #Set up how the model works
  belongs_to                :contest
  belongs_to                :subject

  #Validate the field we're talking about in this post:
  validates_presence_of     :subject_id, 
                              :on => :create,
                              :if => :needs_subject?

.. And later I defined needs_subject? as follows:

  def needs_subject?
    if self.contest.subjects.any?
      return true
      return false
end #End the model.

So this allowed me to only check if there's a subject if there SHOULD BE a subject.

Hope this helps someone.


No comments: