🖥

Make the value of Rails | validation available for external reference

に公開

Solution

It's a simple way. Write the validation value as a constant.

 class Book < ActiveRecord::Base TITLE_MAXIMUM_LENGTH = 100 validates :title, length: { maximum: TITLE_MAXIMUM_LENGTH } end 

reference

 Book::TITLE_MAXIMUM_LENGTH # => 20 

Improvement

It's redundant as it is. Write in one line using the return value of the constant declaration.

 class Book < ActiveRecord::Base validates :title, length: { maximum: TITLE_MAXIMUM_LENGTH = 100 } end 

Supplement

Book.validators_on(:title) method returns an array. It was troublesome to get the value of specific validation, so this method was used.

Please let me know if there is something else.

environment

  • Ruby 2.0.0
  • Rails 4.0.0

Original by

Rails | バリデーションの値を外部から参照できるようにする

About

About this translattion

チャットメンバー募集

何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。

https://line.me/ti/g2/eEPltQ6Tzh3pYAZV8JXKZqc7PJ6L0rpm573dcQ

Twitter

https://twitter.com/YumaInaura

公開日時

2019-04-16

Discussion