14 12 / 2012
Rails 3: Custom validation messages for the same column name using some other column value
Problem: We wanted to add custom validation message, and call the same mysql table column with different names depending on the value of some other field. After much googling I couldn’t find any suitable answers. Posting the solution I came up with, so that it can be of help to others:
Solution:
I couldn’t find solutions using procs, interpolations, etc. I wrote a custom validator, as all the columns are available there. Below is the sample code:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Link < ActiveRecord::Base | |
validate :url_presence | |
def url_presence | |
errors.add(:base, "#{Link.url_label(linktype)} can't be blank.") if url.blank? | |
end | |
def self.url_label(linktype) | |
{"web" => "Web URL", "video" => "Video URL", "audio" => "Audio URL", "ecommerce" => "Shop URL", | |
"page" => "Page number", "email" => "Email"}[linktype] || "URL" | |
end | |
end |
Please note that linktype and url are columns in the links table.
Also answered a related question on Stackoverflow here: