ruby-on-rails - 如何在 Ruby on Rails 5 中验证 pg 数组长度?

标签 ruby-on-rails arrays postgresql validation model

如何验证我的 Note 模型有多少个标签?我目前的模型:

# == Schema Information
#
# Table name: notes
#
#  id              :integer          not null, primary key
#  title           :text
#  body            :text
#  organization_id :integer
#  created_at      :datetime         not null
#  updated_at      :datetime         not null
#  tags            :string           default([]), is an Array
#

# Note represents a saved Note that belongs to an organization.
class Note < ApplicationRecord
  belongs_to :organization
  validates :title, :body, presence: true
end

tags是数据库中的一个pg数组。

最佳答案

Rails 将在内部处理转换,因此您只需要担心处理 Ruby 数组对象。

验证看起来像这样:

class Note < ApplicationRecord
  validates :tags, length: {
    maximum: 10,
    message: 'A note can only have a maximum of 10 tags'
  }
end

it 'is invalid with more than 10 tags' do
  tags = %w(1 2 3 4 5 6 7 8 9 10 11)
  note = build(:note, tags: tags)
  note.valid?
  expect(note.errors[:tags])
    .to include('A note can only have a maximum of 10 tags')
end

关于ruby-on-rails - 如何在 Ruby on Rails 5 中验证 pg 数组长度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41423132/

相关文章:

ruby-on-rails - 为什么我不能使用 RVM 在 Lion 上安装 Rails?

java - 在 Java 中使用 toString() 打印数组

java - 根据单词数组检索句子

perl - 为 SQL 查询的结果分配一个标量

ruby-on-rails - activeadmin 中的嵌套表单不保存更新

ruby-on-rails - 如何清理 Rails 中的属性值

ruby-on-rails - Rails Time.zone 解析没有按预期工作

java - 设置传递给函数的数组变量

sql - 如何使用 postgresql 计算排列?

sql - 新表中每个项目的前 3 - postgres