Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Ruby Rails Routes and Resources Routes to Create Actions Controller Action to Create Pages

Yiheng Chu
Yiheng Chu
8,465 Points

Why I can't use redirect_to '/pages/:id'? It said the 'id' params doesn't passed into the #show action.

All info is above. Thank you!

1 Answer

Jay McGavren
STAFF
Jay McGavren
Treehouse Teacher

redirect_to("/pages/:id") will literally redirect the browser to load the path "/pages/:id". So if you have a get "/pages/:id", to: "pages#show" route set up, then when show is called, params[:id] will be set to the string ":id", which is not what you want.

Instead, you should pass redirect_to a model object that has its id attribute set:

redirect_to @page

Or you should interpolate the ID into a string, and pass that to redirect_to:

redirect_to "/pages/#{@page.id}"

Here's what it would look like in a controller action:

  def create
    @page = Page.new(page_params)

    if @page.save
      redirect_to @page, notice: 'Page was successfully created.'
    else
      render :new
    end
  end