2016-11-03 56 views
1

PostgreSQL將其他數據類型添加到Active Record默認值。
請參閱PostgreSQL documentation,List of available datatypes在Stackoverflow和Active Record and PostgreSQL在RailsGuides。
對於array數據類型,需要在遷移中添加array: true。例如:用於陣列數據類型的數據類型

create_table :books do |t| 
    t.string 'title' 
    t.string 'tags', array: true 
    t.integer 'ratings', array: true 
end 

應在Book模型中使用什麼樣的驗證嗎?
如果整數是一個非數組數據類型我會使用:

validates :ratings, numericality: { only_integer: true, greater_than: 0 } 

這會驗證是正確的情況下也ratings是數組的數據類型?
我有興趣驗證數組元素而不是數組本身。

回答

1

AFAIK沒有內置驗證這種情況。

你可以自定義一個寫:

validate :valid_ratings 

private 

def valid_ratings 
    if everything_is_ok 
    true 
    else 
    errors.add(:ratings, 'ratings is invalid') if something_is_wrong 
    end 
end