default_url_options and rails 3

2019-01-06 16:18发布

As ActionController::Base#default_url_options is deprecated, I wonder how to set default url options in rails3. The default url options are not static but dependent of the current request.

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

Thanks, Corin

4条回答
霸刀☆藐视天下
2楼-- · 2019-01-06 16:54

For Rails 3 specifically, the canonical way to do it is by adding a default_url_options method to your 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

I just had to figure this out myself, so I know it works.

This is adapted from the Rails 3 Guide:
http://guides.rubyonrails.org/v3.2.21/action_controller_overview.html#default_url_options

查看更多
时光不老,我们不散
3楼-- · 2019-01-06 16:55

To set url options for current request use something like this in your controller:

class ApplicationController < ActionController::Base

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

end

Now, :profile => current_profile will be automerge to path/url parameters.

Example routing:

scope ":profile" do
  resources :comments
end

Just write:

comments_path

and if current_profile has set to_param to 'lucas':

/lucas/comments
查看更多
forever°为你锁心
4楼-- · 2019-01-06 16:56

I believe the preferred method is to now tell the router to handle this:

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

You can put this line in either routes.rb or an initializer. Whichever you would prefer. You could even put it in your environment configs if the values change based on your environment.

查看更多
Evening l夕情丶
5楼-- · 2019-01-06 17:02

That apidock.com link is misleading. default_url_options is not deprecated.

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

查看更多
登录 后发表回答