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

我们两清 提交于 2019-12-07 04:05:21

问题


I have a model that has paperclip attachments.

The model might be used in multiple rails apps

I need to return a full (non-relative) url to the attachment as part of a JSON API being consumed elsewhere.

I'd like to abstract the paperclip aspect and have a simple virtual attribute like this:

  def thumbnail_url
    self.photo.url(:thumb)
  end

This however only gives me the relative path. Since it's in the model I can't use the URL helper methods, right?

What would be a good approach to prepending the application root url since I don't have helper support? I would like to avoid hardcoding something or adding code to the controller method that assembles my JSON.

Thank you


回答1:


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"



回答2:


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



回答3:


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.



来源:https://stackoverflow.com/questions/2695393/rails-building-an-absolute-url-in-a-models-virtual-attribute-without-url-help

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