Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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

Joey Zheng
Joey Zheng
19,319 Points

Why can't I use redirect_to method to redirect to an object?

I use this code in my pages controller:

def create
    params_page = params.require(:page).permit(:title, :body, :slug)
    @page = Page.new(params_page)
    @page.save
    redirect_to @page
end

However when I clicked submit button, it said:

NoMethodError in PagesController#create 
undefined method `page_url' for #<PagesController:0x9c9d0b0>
Extracted source (around line #18): 
16  @page = Page.new(params_page)
17  @page.save
18  redirect_to @page
19  end
20
21  end 

What is the problem? Thanks.

1 Answer

Jay McGavren
STAFF
Jay McGavren
Treehouse Teacher

redirect_to @page requires that a page_url method be defined that takes a Page object as an argument.

There are a couple different ways to define that method. One is to ensure your routes.rb file has a line like this:

get    '/pages/:id',      to: 'pages#show', as: 'page'

The as: 'page' part is what names the route and generates the page_url method.

Yes, thank you