Home > Software engineering >  Trying to redirect user to newly created post using Rails
Trying to redirect user to newly created post using Rails

Time:04-12

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

CodePudding user response:

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

CodePudding user response:

You have to have a fallback when post doesn't save due to validation errors. You can only redirect when post is created and has an id.

# POST /posts
def create
  @post = Post.new(post_params)

  respond_to do |format|
    if @post.save
      redirect_to post_url(@post), notice: "Post was successfully created."
    else
      render :new, status: :unprocessable_entity
    end
  end
end

private

  def post_params
    params.require(:post).permit(:date, :rationale)
  end

Use rails generators when you need simple set up like that

# just controller
bin/rails generate scaffold_controller Post

# all in one go
bin/rails generate scaffold Post rationale date:date
  • Related