Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails route to username instead of id

Tags:

I am trying to change the rails routes from /users/1 to /username. I currently set this up so it works for the actions of showing and editing. The actual issue is that when I go to update the user by using:

<%= form_for @user do |f|%> 

It never updates, because the update action is routed to /users/:id. Is there any way to route this so that it works for /username? (which is the route that is rendering in my forms as the action). I've been scratching my head over this one for a while now.

EDIT:

The issue isn't routing to username, that it working correctly. The issue is that the form routes to /username for update, however the update route for users is still /users/:id instead of :/id.

I tried updating my routes to this, but to no avail:

match '/:id', :to => "users#show", :as => :user match '/:id', :to => "users#update", :as => :user, :via => :put match '/:id', :to => "users#destroy", :as => :user, :via => :delete 

EDIT:

Doh! This fixed the issue:

match '/:id', :to => "users#show", :as => :user, :via => :get 
like image 280
jwhiting Avatar asked Oct 12 '11 04:10

jwhiting


People also ask

How do I use the root method in rails?

You can specify what Rails should route '/' to with the root method: You should put the root route at the top of the file, because it is the most popular route and should be matched first. The root route only routes GET requests to the action. You can also use root inside namespaces and scopes as well. For example:

How do I customize the default routes and helpers in rails?

While the default routes and helpers generated by resources will usually serve you well, you may want to customize them in some way. Rails allows you to customize virtually any generic part of the resourceful helpers. The :controller option lets you explicitly specify a controller to use for the resource.

What is resource routing in rails 2?

2 Resource Routing: the Rails Default. Resource routing allows you to quickly declare all of the common routes for a given resourceful controller. Instead of declaring separate routes for your index, show, new, edit, create, update and destroy actions, a resourceful route declares them in a single line of code.

How to use a dot in a route name?

If you need to use a dot within an :id add a constraint which overrides this - for example id: / [^\/]+/ allows anything except a slash. The :as option lets you override the normal naming for the named route helpers.


1 Answers

In your user model:

def to_param   username end 

The to_param method on ActiveRecord objects uses, by default, just the ID of the object. By putting this code in your model, you're overwriting the ActiveRecord default, so when you link to a User, it will use the username for the parameter instead of id.

like image 99
bricker Avatar answered Dec 06 '22 15:12

bricker