Skip to content

Instantly share code, notes, and snippets.

@sam452
Created December 19, 2012 00:54
Show Gist options
  • Save sam452/4333492 to your computer and use it in GitHub Desktop.
Save sam452/4333492 to your computer and use it in GitHub Desktop.
Trying to validate two fields conditionally. If either video_url or video_title is not blank then the other must not be empty.
require 'video_title_validator'
class Post < ActiveRecord::Base
attr_accessible :body, :title, :image, :video_title, :video_url
validates :video_url, :presence => true, :if => :video_title_blank?
belongs_to :author, class_name: "User"
has_many :comments
has_many :parent_comments, class_name: "Comment", conditions: { parent_comment_id: nil }
has_many :images
mount_uploader :image, ImageUploader
end
class VideoTitleValidator < ActiveModel::Validator
def video_title_blank?(record)
if record.video_title
record.errors[:base] << "Video must have a title"
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment