【发布时间】: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