I’m creating a Rails app for managing individual items. Each item has an item number (zero padded, 4 digit number, e.g. 0002 or 0212 or 1002), which I would like to use in the urls for the application. If I currently navigate to /items/2 I get the item with id = 2 and not the item with item_number = 2. My routes.rb file contains only resources :items; how would I go about allowing for this to pull out the items by item number?
I’m creating a Rails app for managing individual items. Each item has an item
Share
Override the
to_parammethod in your Item model:You don’t have to change anything in your routes.
You’ll just have to find the items using
find_by_item_number(params[:id])Just so you know: if you wanted to display the name of the item in the url, you could do the following:
What’s great about that, is that “1-item-name”.to_i is
1! So you would not have to change your find methods everywhere.