'Trying to redirect user to newly created post using Rails

I have a Rails controller that should redirect me to a newly created post:

class PostsController < ApplicationController
    def index
    end

    def new
        @post = Post.new
    end

    def create
        @post = Post.new(params.require(:post).permit(:date, :rationale))
        @post.save
        redirect_to @post
    end

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

the view for the show method is:

<%= @post.inspect %>

The following test passes:

it 'can be created from new form' do
      visit new_post_path
      fill_in 'post[date]', with: Date.today
      fill_in 'post[rationale]', with: "Some rationale"
      click_on "Save"
      expect(page).to have_content("Some rationale")
  end

however when I run through the browser, the redirect only goes to the index /posts

Expected Behaviour: The user should be redircted to the view show and see the newly created post

If I hard code the id into the redirect I can see the newly created post



Solution 1:[1]

you can find route using this, rails routes then find the routes with the posts id, either you want to use prefix/ URI pattern. in this case, seems like you're using show. then you can use redirect_to '/post/:id/show' for URI pattern, the id should be @post.id

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Angry Cat