views:

1286

answers:

3

Hello, rails friends. I'm struggling here with a problem: I have a controller questions which has action new. Whenever I need to create new question, I'm typing

/questions/new

What changes to routes.rb should I make to change the URI to

/questions/ask


Thank you. Valve.

A: 

Which version of rails?

Generally the default route should catch anything like /:controller/:action, so you could just create an ask method in your questions controller. Take a look at the api documentation for named_route and map_resource if you want something a bit smoother to work with.

Jason Watkins
Hello, Jason. Rails 2.2.2.I try to use RESTful routing, so I deleted the default two routes (controller/action/id and the other).I'd expect something likemap.resources :questions, :action=>{:new=>:ask}if it is possible.Thanks.
Valentin Vasiliev
+5  A: 

Try this:

map.ask_question   '/questions/ask', :controller => 'questions', :action => 'new'

Then you'll have a named route and you can:

link_to "Ask a question", ask_question_path
Christian Lescuyer
Hi, Christian.Will this enable me to type http://mySite/questions/ask and go toask controller? Please note that I'm trying to use RESTful routing.Thanks,Valve.
Valentin Vasiliev
Christian's solution points http://mySite/questions/ask to the new action in the QuestionsController, which will (by default) render app/views/questions/new.html.erb. It does _NOT_ stop users from going to /questions/new to achieve the same result.
James A. Rosen
@Valve it will go to the questions controller with action new. It is RESTful indeed as you're using both the URL and request type.@Gaius you're right. To prevent users from going to /questions/new you have to remove the default route at the end of the routes.rb file.
Christian Lescuyer
+1  A: 

If you are using RESTful routes maybe you'd like to use map.resources for your questions.

To rename the action urls you may do this:

map.resources :questions, :path_names => { :new => 'ask', :delete => 'withdraw' }

(I added delete for the sake of the example)

ilpoldo