0

我不能让它通过:

  %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'

请帮忙。

4

2 回答 2

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 路由。

于 2012-09-07T18:20:15.493 回答
0

我想如果你不喜欢以下的原始代码

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 以match获取get.

于 2012-09-08T05:33:14.037 回答