Validations
Now what if we don’t want people entering blank data into our forms later on? Validations are the answer. We can validate the data before its entered into the database and provide error messages if something goes wrong.
Lets start with the Forum model. We’ll have a form where people can enter a title and a description for their forum, and we want to make sure that they’ve entered both, and that the description is longer than four characters. For this we’ll use validates_presence_of and validates_length_of.
app/models/forum.rb
class Forum < ActiveRecord::Base has_many :topics has_many :posts, :through => :topics validates_presence_of :title, :description validates_length_of :description, :minimum => 4 end
So we’ve simply called these two methods in our model and those validations will be checked when we go to save a forum object. We’ve passed two arguments to validates_presence_of, and these can be passed as symbols or strings. We’ve also passed two arguments to validates_length_of, the second of which is :minimum => 4 which tells the method that the length of description has to be at least 4 characters long. All validations take a very helpful option, :message. With this option you can specify a message prefixed by the field name that failed the validation, like this:
app/models/forum.rb
class Forum < ActiveRecord::Base has_many :topics has_many :posts, :through => :topics validates_presence_of :title, :description, :message => "must not be blank, on penalty of defenestration!" validates_length_of :description, :minimum => 4 end
Moving on to our Topic model now, we need to make sure that a topic has a subject and it’s not shorter than 4 characters long.
app/models/topic.rb
class Topic < ActiveRecord::Base belongs_to :user belongs_to :forum has_many :posts validates_presence_of :subject validates_length_of :subject, :minimum => 4 end
And the post model:
app/models/post.rb
class Post < ActiveRecord::Base belongs_to :topic belongs_to :user validates_presence_of :text validates_length_of :text, :minimum => 10 end
You can find more information about these and other validation methods at noobkit.com’s validations page.
