我无法通过:
%w[home help about contact].each do |page|
get :controller => 'static_pages', :action => page
end
我试图重构这段代码:
get 'static_pages/home'
get 'static_pages/help'
get 'static_pages/about'
get 'static_pages/contact'
请帮忙。
答案 0 :(得分:1)
static_pages = %w(home help about contact).map {|p| p.to_sym}
resources :static_pages, only: static_pages do
static_pages.each do |page|
get page, on: :collection
end
end
呈现
$ rake routes
home_static_pages GET /static_pages/home(.:format) static_pages#home
help_static_pages GET /static_pages/help(.:format) static_pages#help
about_static_pages GET /static_pages/about(.:format) static_pages#about
contact_static_pages GET /static_pages/contact(.:format) static_pages#contact
使用only: static_pages
不生成CRUD路由。
答案 1 :(得分:0)
我想如果你不喜欢original code:
root to: 'static_pages#home'
match '/help', to: 'static_pages#help'
match '/about', to: 'static_pages#about'
match '/contact', to: 'static_pages#contact'
你希望获得相同的路线,你可以使用简单的循环:
root to: 'static_pages#home'
%w(help about contact).each do |page|
get "#{page}" => "static_pages##{page}"
end
虽然对我而言,这似乎不足以证明它的合理性。
要修复代码中的错误,请使用:
%w(home help about contact).each do |page|
get "/#{page}", :controller => 'static_pages', :action => page
end
检查api for match
是否有get
的有效参数。