default_url_options and rails 3

时间秒杀一切 提交于 2019-11-27 01:28:28

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
Dylan Markow

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.

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

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

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

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

In the developemnt.rb / test.rb, can be more concise as following:

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

  routes.default_url_options[:host] = 'localhost:3000'
end
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!