Reputation: 536
I want my users to be able to view /categories/comedy/ and see all posts available in the comedy category. Problem is that in my database all categories are with a capital, so comedy is Comedy. This means /categories/Comedy/ does work and /categories/comedy/ doesn't. I know it doesn't seem like a big deal but in the perspective of being as user-friendly as possible it is.
def show
if @category = Category.find_by_name.(params[:id])
@stories = @category.stories
else
redirect_to categories_path
flash[:error] = "There is no such category"
end
end
This is the code in my controller. I think I might have to uppercase the first letter at all time, but since I'm a newbie to Rails I have absolutely no idea how to accomplish this.
Thank you for reading this and hopefully thanks for your help! Mats
Upvotes: 0
Views: 310
Reputation: 35533
Use titleize
if all words in the category name have their first letter capitalized:
Category.find_by_name(params[:id].titleize)
Otherwise, use humanize
:
Category.find_by_name(params[:id].humanize)
Which one you choose will only matter for multi-word category names - titleize
will make the first letter of all words uppercase, humanize
will make the first letter of the first word uppercase.
humanize
also has the side-effect of removing trailing _id
from the string - which probably won't be an issue in your case.
I should also mention that database comparisons are often case-insensitive, so for non parameterized strings, this may not be necessary. It becomes more necessary when you parameterize
the route path, in which case multiple words become hyphen delimited.
Upvotes: 1