Jake
Jake

Reputation: 1380

In Rails, how to display a name instead of id?

What I'm looking to do is have the url display something like: books/grapesofwrath

However right now it's simply books/32

In my controller I have the following:

def show
 @book = Book.find(params[:id])
 @header = true
 @metatoon = true
end

Everything works fine with this but I want the url to be using the book name. So I changed it to:

 def show
 @book = Book.find_by(book_name: params[:book_name])
 @header = true
 @metatoon = true
end

Cool. I think it's correct but I end up with the following error when loading a show page:

undefined method `book_image' for nil:NilClass

I feel like I was wrong in how I change the params to search by book name. Is there something I should be doing in route?

Upvotes: 2

Views: 353

Answers (1)

VAD
VAD

Reputation: 2401

You may find useful friendly_id gem. It's created exactly for those kind of stuff.

Upvotes: 3

Related Questions