Rails, in a route like /books/:slug, :to => 'books#show', slug: /.*?/ what is slug: /.*?/ doing?

Viewed 45

I have come across a route like /books/:slug, :to => 'books#show', slug: /.*?/ in an application I have been working on. I am curious what does this part do slug: /.*?/ ?

1 Answers

Its a misguided attempt at slugging.

It creates a route that matches:

/books/1
/books/abcd-absc

But not:

/books/1/2
/books/abcd-absc/2

slug: /.*?/ is a completely pointless regex constraint since .* matches everything.

The end result is a route that does the exact same thing as the GET /books/:id generated by the conventional resources :books does except that the parameter is now named :slug (woopty do!) - the main reason its so misguided is that this route will conflict with the former.

You can really just do simple slugging that looks up a record by id or slug with:

@book = Book.where(id: params[:id]).or(Book.where(slug: params[:id])).first!
Related