有没有更好的方法在Rails 3路由中使用with_options?

时间:2010-12-14 01:13:44

标签: ruby-on-rails routing routes ruby-on-rails-3 rails-routing

以下是我的Rails 2路线:

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

如何将此类内容转换为Rails 3?只是以同样的方式继续使用with_options?在某些情况下它变得更加晦涩,因为它不是做

match '' => 'foo#for_blank'

我在做

match '', :action => 'for_blank'

3 个答案:

答案 0 :(得分:2)

是的,with_options仍可在Rails 3中运行。试试这个:

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

:via选项用更好的语法替换你丑陋的conditions哈希。

答案 1 :(得分:2)

像这样:

#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

答案 2 :(得分:1)

尝试坚持路线提供的方法。它们在Rails 3中非常强大,应该提供您需要的一切。有关详细信息,请参阅http://guides.rubyonrails.org/routing.html