0

I have a rails 4 app with a Post model and a Tag model. Those models are related by an HABTM relation.

class Post < ActiveRecord::Base
  has_and_belongs_to_many :tags
...
end

The Post model has an "image" column and validates its correctness trough a format validation still allowing blank.

validates :image, 
    format: { with: /\Ahttps\:\/\/s3.*amazonaws\.com.*\.png\z/ , message: 'Must be a valid url within S3 bucket' },
    allow_blank: true

I need to add a validation that doesn't allow Post.image to be blank if a particular tag is selected. For example if Tag.name == "foo" is associated to this post, then Post.image cannot be blank.

This is the model spec that should pass:

it 'should not allow a post with tag name "foo" to have an empty image' do
  mytags = [create(:tag, name: 'foo')]
  expect(build(:post, image: '', tags: mytags)).to_not be_valid
end

What validation would make my test pass?

TopperH
  • 2,183
  • 18
  • 33

1 Answers1

1
class TagValidator < ActiveModel::Validator
  def validate(record)
    record.tags.each do |tag|
      if tag.name == "foo" && record.image.blank?
        record.errors[:base] << "Image name cannot be blank for this tag"
      end
    end
  end
end


class Post < ActiveRecord::Base
  validates_with TagValidator
end
TopperH
  • 2,183
  • 18
  • 33
Ruby_Pry
  • 237
  • 1
  • 10