0

我有一个带Post模型和标签模型的rails 4应用程序。这些模型与HABTM关系有关。验证以allow_blank,除非选择了某种关系

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

Post模型具有“图像”列,并通过格式验证验证其正确性,仍然允许空白。

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

我需要添加一个验证不允许如果选择一个特定的标签Post.image是空白。例如,如果Tag.name ==“foo”与此帖相关联,则Post.image不能为空。

这是在型号规格应通过:

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 

验证什么会让我的测试通过了吗?

回答

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