【问题标题】:Validation to allow_blank unless a certain relation is selected除非选择了某个关系,否则验证 allow_blank
【发布时间】:2023-03-22 09:26:01
【问题描述】:

我有一个带有 Post 模型和 Tag 模型的 rails 4 应用程序。这些模型通过 HABTM 关系相关。

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

什么验证可以让我的测试通过?

【问题讨论】:

    标签: ruby-on-rails validation activerecord has-and-belongs-to-many


    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多