1
1

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 3 years have passed since last update.

[Rails] 投稿できない原因がform_withにあった件

Last updated at Posted at 2020-10-29

はじめに

以前、twitter的なものを作成している受講生さんから「ボタン押してるのに投稿できない!エラー文も何も出ない!(涙)」っていう質問があり、僕自身もその原因をすぐに突き止めることができなく苦労したので同じような悩みを持つ人のために投稿します。

バージョン

ruby 2.5.7
Rails 5.2.4.3

原因と解決法

books_controller.rb
def create
   @book = Book.new(book_params)
   @book.user_id = current_user.id
   if @book.save
      redirect_to book_path(@book)
   else
      @books = Book.all
      render 'index'
end

...と、コントローラーにはsaveできたらbook_path(@book)のページに行け!できない時はindexのページに行け!と指定してるのに

_list.html.erb
<%= form_with model:book, url:root_path do |f| %>
   
<% end %>

...と、ビューにはボタン押されたらroot_pathのページに行け!という謎の別の指定がされていました。

なので、

_list.html.erb
<%= form_with model:book do |f| %>
   
<% end %>

...のようにビューのurlの部分を全て削除してあげたら問題なく投稿できるようになりました。めでたし。

最後に

form_withのurlの部分の記述がおかしいとrouting errorの原因にもなってしまうので気をつけましょう。

form_withの使い方について詳しく知りたい方はこちらの資料がおすすめです。

1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?