2017-01-02 11 views
0

Noteモデルのタグの数を確認するにはどうすればよいですか?現在、私のモデル:Ruby on Rails 5でpg配列の長さを検証する方法は?

# == 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配列です。

答えて

2

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 
関連する問題