2011-05-23 38 views
17

由於ActionController :: Base#default_url_options已被棄用,我不知道如何在rails3中設置默認的url選項。默認的url選項不是靜態的,而是取決於當前的請求。default_url_options和rails 3

http://apidock.com/rails/ActionController/Base/default_url_options

感謝, 科林

+0

'的ActionController ::基地#default_url_options' [*不是*棄用(http://edgeguides.rubyonrails.org/action_controller_overview.html#default:

這是從軌道3指南適於-url選項)。 – Mohamad 2015-08-01 14:10:13

回答

24

要爲當前請求使用這樣的網址選項控制器:

class ApplicationController < ActionController::Base 

    def url_options 
    { :profile => current_profile }.merge(super) 
    end 

end 

現在:配置=> CURRENT_PROFILE將automerge到路徑/ URL參數。

示例路由:

scope ":profile" do 
    resources :comments 
end 

只要寫:

comments_path 

如果CURRENT_PROFILE已成立to_param爲 '盧卡斯':

/lucas/comments 
+0

謝謝!這是「官方」導軌3.0/3.1的方式嗎? – gucki 2011-06-05 19:34:20

+0

太糟糕了,它在聲明爲受保護的時候會引發異常(否則它會作爲操作公開)。所以它不起作用。 – gucki 2011-06-06 17:33:39

+4

它適用於我在真實項目中,我不知道爲什麼你認爲它作爲一個動作公開,只是從你的路線中刪除默認路由/:控制器/(:行動)。這種方法必須是公開的。 – 2011-06-08 16:33:39

24

我認爲首選的方法是現在告訴路由器來處理:

Rails.application.routes.default_url_options[:foo]= 'bar' 

你可以把此行要麼routes.rb或初始化。無論你喜歡什麼。如果值根據您的環境而改變,您甚至可以將其放入環境配置中。

+1

但我怎麼能使這依賴於當前的請求,所以例如訪問實例變量? – gucki 2011-05-23 18:23:17

+0

葉,它不是線程安全的。我通過自定義方法和Thread.current做了 – 2011-08-15 17:05:55

+2

看起來這是Rails 3.2的。 – aceofspades 2012-03-19 18:34:56

0

對於Rails 3中明確,規範的方式來做到這一點是通過添加default_url_options方法您ApplicationController

class ApplicationController < ActionController::Base 
    def default_url_options 
    { 
     :host => "corin.example.com", 
     :port => "80" # Optional. Set nil to force Rails to omit 
         # the port if for some reason it's being 
         # included when you don't want it. 
    } 
    end 
end 

我只是自己弄清楚了這一點,所以我知道它的工作原理。
http://guides.rubyonrails.org/v3.2.21/action_controller_overview.html#default_url_options