LoginSignup
3
3

More than 3 years have passed since last update.

Railsのform_forとRouting Error

Posted at

Railsのform_forとRouting Error

今回の記事の目的

Railsでform_forで編集などのviewを書いている時によくRouting Errorが起きていたことについて今回やっと解決したのと色々調べているうちに得られた知見をまとめてみました。

ちなみにteratailに初投稿して解答を頂き解決しました。
こちらです。


https://ruby-rails.hatenadiary.com/entry/20140813/1407915718
今回エラーが起きたのはこちらのサイトのミニBlog作成、
4.2. 最初のフォームのところです。

問題点

editからupdateに送信時にrouting errorが起こりました。

エラーメッセージ

Routing Error
No route matches [PATCH] "/posts.1"
Rails.root: /Users/xxxxx/workz/blog

Application Trace | Framework Trace | Full Trace
Routes
Routes match in priority from top to bottom

ソースコード

routes.rb

Rails.application.routes.draw do

  resources :posts

end

post.controller.rb

def edit
  @post = Post.find(params[:id])
end

def update
  @post = Post.find(params[:id])
  if @post.update(post_params)
      redirect_to @post
    else
      render :edit, status: :unprocessable_entity
    end
end

private
def post_params
  params.require(:post).permit(:title, :text)
end

edit.html.erb

<h1>投稿を更新</h1>
<%= form_for :post, url: posts_path, method: :patch do |f| %>
  <% if @post.errors.any? %>
    <div id="error_explanation">
      <h2><%= @post.errors.count %>件のエラーが発生したため保存ができませんでした。</h2>
      <ul>
      <% @post.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

試したこと

rake routesでURL一覧を出した時にupgradeのURLが

post PATCH  /posts/:id(.:format)     posts#update

だったので何となくposts_pathだと思ったのですが、
resourcesの対応pathが
| action | path | url |
| index | posts_path | /posts |
| show | post_path(@post) | /posts/1 |
| new | new_post_path | /posts/new |
| edit | edit_post_path(@post) | /posts/1/edit |
| create | posts_path | /posts |
| update | post_path(@post) | /posts/1 |
| destroy | post_path(@post) | /posts/1 |
post_path(@post)を指定する必要がありました。

今回学んだこと

-form_forの役割-
1.form_forは自動でpostに合ったpathを自動で探すので例えばeditからupdateに送る時はmethodにpatchを指定しないといけない。

2.form_forで指定するURLのところはresourcesのところで確認してupdateなど個別のidを持つものは単数形で指定するpost_path(@post)

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