2
5

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.

バリデーションを使って空欄で投稿した時にエラーメッセージを表示したい。

Posted at

まず、modelでバリデーションをかく

book.erb
`validates :name, presence: true`

presence: trueは、空欄でないことを確認してる。

その後にhtmlでエラーメッセージが表示できるようにする

book.html.erb
<%= form_for(@names, url: names_path) do |f| %>
<% if @names.errors.any? %>
<%= @names.errors.count %>件のエラー
<% @names.errors.full_messages.each do |message| %>
<%= message %>
<% end %>

次にコントローラーで

books_controller.rb
def create
        @name = Name.new(name_params)
if @book.save
          redirect_to books_path
        else
          render :new
        end

private
    def book_params
        params.require(:book).permit(:book_name, :opinion)
    end

@name = Name.new(name_params)
で新規投稿できるよっていうnewが呼ばれてくる
requireでbookを指定してる

条件分岐で、空欄じゃなかったら redirect_to books_pathにいって、空欄だったら renderでnewにいくかな

2
5
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
2
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?