Rails - building an absolute url in a model's virtual attribute without url helper

不羁岁月 提交于 2019-12-05 07:06:29

The url helper takes the host name from the incoming request. A model doesn't need a request to exist, hence why you can't use the URL helpers.

One solution is to pass the request hostname to the thumbnail url helper.

def thumbnail_url(hostname)
  self.photo.url(:thumb, :host => hostname)
end

Then call it from your controllers / views like this

photo.thumbnail_url(request.host)

It turns out that there isn't really a foolproof way to get the host name of a server. If a user adds an entry to their /etc/hosts file, they can access the server with whatever host name they want. If you rely the incoming request's hostname, it could be used to break the thumbnails.

Because of this, I generally hardcode my site's host name in an initializer. e.g. put this in config/initializers/hostname.rb

HOSTNAME = 'whatever'

-- edit --

It looke like in rails 3 you have to provide the :only_path => false parameter to get this to work. Here's an example from the console:

>> app.clients_path :host => 'google.com', :only_path => false
=> "http://google.com/clients"

In Rails 3.0, the include given above results in a deprecation warning.

In Rails 3.0, use the following code instead to include url helpers:

class Photo < ActiveRecord::Base
  include Rails.application.routes.url_helpers
end

I've found you can have URL helpers in models with the following:

class Photo < ActiveRecord::Base
  include ActionController::UrlWriter

  def thumb_url
     thumb_url(self)
  end
end

Caution though - I found this picked up the HOST, but not the port. You can investigate ActionController::default_url_options for more detail.

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