17

ActionController :: Base#default_url_optionsは非推奨になっているため、rails3でデフォルトのURLオプションを設定する方法を知りたいと思います。デフォルトのURLオプションは静的ではありませんが、現在のリクエストに依存しています。

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

ありがとう、コリン

4

5 に答える 5

26

現在のリクエストのURLオプションを設定するには、コントローラーで次のようなものを使用します。

class ApplicationController < ActionController::Base

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

end

これで、:profile=>current_profileがパス/URLパラメーターに自動マージされます。

ルーティングの例:

scope ":profile" do
  resources :comments
end

書くだけ:

comments_path

また、current_profileがto_paramを'lucas'に設定している場合:

/lucas/comments
于 2011-06-04T22:09:12.853 に答える
24

推奨される方法は、ルーターにこれを処理するように指示することだと思います。

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

この行は、routes.rbまたは初期化子のいずれかに配置できます。どちらでもいいです。環境に基づいて値が変更された場合は、環境構成に含めることもできます。

于 2011-05-23T18:12:40.823 に答える
4

その apidock.com リンクは誤解を招くものです。default_url_options は非推奨ではありません。

http://guides.rubyonrails.org/action_controller_overview.html#default_url_options

于 2012-08-23T19:02:18.470 に答える
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

私はこれを自分で理解しなければならなかったので、それが機能することを知っています。

これは、Rails 3 ガイドから改作されています:
http://guides.rubyonrails.org/v3.2.21/action_controller_overview.html#default_url_options

于 2015-09-24T21:16:41.237 に答える
0

Rails.application.routes.default_url_options[:host]= 'localhost:3000'

developmentemnt.rb / test.rb では、次のように簡潔に記述できます。

Rails.application.configure do
  # ... other config ...

  routes.default_url_options[:host] = 'localhost:3000'
end
于 2019-01-16T03:33:44.580 に答える