0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

バリデーションを設定しよう。 ❏Rails❏

Last updated at Posted at 2019-11-27

バリデーションとは

フォームから送られてきた値が正常な値であるか検証する機能です。
よく使う2つを見ていきましょう。

presence: true
unique: true


# ①値が空ではないか フォームが空の場合は保存できなくします。

モデルに
validates :カラム名, presence: trueを追記

例)tweetsテーブルのtextカラムに入る値を入力必須にしたい↓

tweet.rb
class Tweet < ApplicationRecord
  validates :text, presence: true
end

textを入力しなかった場合にエラーとなり、保存できません。

②値が他と被ってないか

他のレコードに既に同じ値がある場合は保存できなくします。
唯一無二の値のことを、一意な値と言います。

モデルに、
validates :カラム名, unique: trueを追記

例)tweetsテーブルのtextカラムに入る値を一意にしたい↓

tweet.rb
class Tweet < ApplicationRecord
  validates :text, unique: true
end

まったく同じテキストは保存できなくなりました。
おはようとツイートできるのは1人だけ。早いもの勝ちとなります。

エラーメッセージを表示させる

保存できないことを知らせてあげましょう。

new.html.haml
- if @tweet.errors.any?
  %div
    %h2= "#{@tweet.errors.full_messages.count}件のエラーが発生しました。"
    %ul
      - @tweet.errors.full_messages.each do |message|
        %li= message

もしエラーメッセージが表示されない時は以下を疑いましょう。 ・`form_with`の`local: true`が抜けてる。
new.html.haml
= form_with model: tweet do |form| #誤り

= form_with model: tweet, local: true do |form| #正しい

僕はエラーメッセージが表示されなくて、2日間悩みました。


ではまた!
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?