Home>
what I want to know

How nice! Implementing the function. How nice! I want to jump to "likes/create" when I press,
Routes "No route matches" error occurs. I want to know the cause.
Reference site: https://qiita.com/nojinoji/items/2c66499848d882c31ffa

Rails.application.routes.draw do
  post "likes /: id/create" =>"likes # create" ← here!
  get'users/index'=>"users # index"
  get "signup" =>"users # new"
  post "users/create" =>"users # create"
  get "posts/index" =>"posts # index"
  get "posts/new" =>"posts # new"
  post "posts/create" =>"posts # create"
..
..
end


→ No route matches [GET] "/ posts" and an error occurred
So, if you remove it and remove it from Routes,

Rails.application.routes.draw do
  get'users/index'=>"users # index"
  get "signup" =>"users # new"
  post "users/create" =>"users # create"
  get "posts/index" =>"posts # index"
  get "posts/new" =>"posts # new"
  post "posts/create" =>"posts # create"
..
..
end

→ No route matches [POST] "/ likes/1/create" and an error occurs
In this way, I get an error that the Routes do not match.

$rails g model like post: references user: references content: string
$rails db: migrate
class Likee</pre>
<pre><code data-language = "view"><% = link_to "/likes/#{@post.id}/create",: method =>: post, content: "like" do%>Like!<% end%>
def create
    @like = Like.create (user_id: @ current_user.id, post_id: params [: id], content: params [: content])
    @post = @ like.post
    redirect_to ("/ posts")
  end

(Usually I think that content is unnecessary for Like, but I put it for a special reason)

  • Answer # 1

    redirect_to ("/ posts")

    This redirects you, but the behavior at this time may differ slightly depending on the browser.
    (Interpreting the standard document, it seems that the post is correct, but in most cases it is changed to get, so it is confusing.
    Furthermore, if pjax/ajax is involved, the result will change)
    Whether to redirect as post or change the method to get
    The browser you are using happened to be the type that redirects as (?) Post.

    redirect_to ("/ posts", status:: see_other)

    You can force get by doing. (For compatible browsers)

Related articles