In Rails 3.2.2, I want to setup custom URLs (using State 2 digit :abbr, instead of the default by :id)
Reading google results and stackoverflow pages, I’ve come up with this:
Routes
match 'cars/:abbr' => 'states#show', :as => 'state_abbr'
Model
def to_param
abbr
end
Controller
@state = State.find_by_abbr(params[:id])
The state#show page is throwing out errors (undefined method `fullname’ for nil:NilClass), because the routing does not seem to be finding the abbr in the model.
Running rake routes, I get:
root / states#index
state_abbr /cars/:abbr(.:format) states#show
Thanks for your help
You want to use
params[:abbr]notparams[:id]. If you want to use:idchange your route to be'cars/:id'instead of'cars/:abbr'