簡體   English   中英

如何在Ruby on Rails 5中驗證pg數組長度?

[英]How to validate pg array length in Ruby on Rails 5?

如何驗證我的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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM