rails 4 route with route

时间:2013-12-28 19:26:03

标签: ruby-on-rails ruby

这是我的路线设置

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

它工作正常,但我想在此路线中添加一个参数

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

我跑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)

向此路线添加参数的正确方法是什么?

1 个答案:

答案 0 :(得分:8)

应该是

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

如果您要使用messages_message_urlmessages_message_path,请使用带as:选项的命名路线:

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