开发者

Refactoring 'match' in routes.rb

I've read official guide but still have misunderstanding. Is this code able for refactoring?

match '/help',    :to => 'home#help'
match '/contact', :to => 'home#contact'
match '/about',   :to => 'home#about'

help, contact and about are the only actions in the contr开发者_如何学Gooller home.


I did this on a hunch and it's not mentioned in the documentation, but it looks like it works (I'm on rails 3.1):

controller :home do
  get 'help'
  get 'contact'
  get 'about'
end

This also creates the help_url, help_path, etc helpers.

One warning though, this restricts the http verbs to GET. If you have a POST action (as an example, for a contact form), you could do either:

controller :home do
  get 'help'
  match 'contact', :via => [:get, :post]
  get 'about'
end

or just:

controller :home do
  get 'help'
  match 'contact'
  get 'about'
end

which will allow all http verbs on the contact route. But I find it better to be explicit about the accepted verbs.


You should be able to use rails shorthand here and do:

match 'home/help'
match 'home/contact'
match 'home/about'

Since the method names match this should work.


you could of course do

match '/:action', :controller => :home, :constraints => { :action => /^(help|contact|about)$/ }

but this is neither prettier, nor really shorter

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜