14
7

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 備忘録】errors.add の書き方

Last updated at Posted at 2019-06-19

はじめに

errors.add……の書き方をよく忘れてしまうので備忘録。

条件

ProjectモデルとGenreモデルがhas_and_belongs_to_manyで中間テーブルを通してアソシエーションされている。

projectをcreateするとき、該当のprojectのGenreも登録している。

erros.addをvalidateに記述する

project.rb
class Project < ApplicationRecord
  has_and_belongs_to_many :genres

  validates :name, presence: true, length: { maximum: 200 }
  
  
  
  validate :has_genres?

  def has_genres?
    errors.add(:genres, "を選んでください") if self.genres.blank?
  end

end

きちんとi18nとエラーを表示をする設定をviewに追記すれば、
Genreを登録しなかったときにErrorMessageが表示されます。

new.html.erb
          <% @project.errors.full_messages.each do |msg| %>
            <div class="alert alert-danger">
              <%= msg %>
            </div>
          <% end %>
スクリーンショット 2019-06-19 17.11.07.png
14
7
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
14
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?