Is there a better way to do with_options in Rails 3 routes?
Here are my Rails 2 routes:
map.with_options :controller => 'foo', :conditions => { :method => :post } do |foo|
foo.one 'one', :action => 'one'
foo.two 'two', :action => 'two'
foo.with_options :special_flag => 'true', :path_prefix => 'special_prefix',
:conditions => { :开发者_运维百科method => :get } do |bar|
bar.three '', :action => 'for_blank'
bar.four 'another', :action => 'for_another'
end
end
How do I convert this sort of thing to Rails 3? Just keep using with_options in the same way? It becomes wordier in some cases because instead of doing
match '' => 'foo#for_blank'
I'm doing
match '', :action => 'for_blank'
Yeah, with_options
still works in Rails 3. Try this out:
map.with_options :controller => 'foo', :via => :post do
match 'one', :action => 'one' #automatically generates one_* helpers
match 'two', :action => 'two' #automatically generates two_* helpers
foo.with_options :special_flag => 'true', :path => 'special_prefix', :via => :get do
match '', :action => 'for_blank'
match 'another', :action => 'for_another', :as => "four" # as will change the helper methods names
end
end
The :via
option replaces your ugly conditions
hash with a much nicer syntax.
Like this:
#JSON API
defaults :format => 'json' do
get "log_out" => "sessions#destroy", :as => "log_out"
get "log_in" => "sessions#new", :as => "log_in"
get "sign_up" => "users#new", :as => "sign_up"
resources :users, :sessions
end
Try to stick to the methods the routes provide. They are very powerful in Rails 3 and should provide everything you need. See http://guides.rubyonrails.org/routing.html for more details
精彩评论