4

Here is my route settings

resources :messages do collection do get 'message' end end 

It works fine but I would like to add a parameter to this route

resources :messages do collection do get 'message/:username' end end 

I got an error when I ran rake routes

rake aborted! missing :action /home/li/data/git/projectname/config/routes.rb:5:in `block (4 levels) in <top (required)>' /home/li/data/git/projectname/config/routes.rb:4:in `block (3 levels) in <top (required)>' /home/li/data/git/projectname/config/routes.rb:3:in `block (2 levels) in <top (required)>' /home/li/data/git/projectname/config/routes.rb:2:in `block in <top (required)>' /home/li/data/git/projectname/config/routes.rb:1:in `<top (required)>' /home/li/data/git/projectname/config/environment.rb:5:in `<top (required)>' Tasks: TOP => routes => environment (See full trace by running task with --trace) 

What is the right way to add a parameter to this route?

1 Answer 1

11

It should be

resources :messages do collection do get 'message/:username' => :message end end 

If you want to use messages_message_url and messages_message_path, use a named route with the as: option:

resources :messages do collection do get 'message/:username' => :message, as: 'messages_message' end end 
Sign up to request clarification or add additional context in comments.

3 Comments

why get 'message/:username' => 'message' not working?
@wwli I'm not sure, I think get 'message' is a shortcut for get 'message' => 'message', and it can't work with dynamic segment.
Sorry to bug you again, I tried to run rake routes how come the prefix is empty. And I tried to use message_messages_path I met an error undefined method message_messages_path` Some setting I am missing for this route?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.