简体   繁体   中英

How to provide local image urls from Rails 5 API only app

We have an API only, Rails 5 app (so no pipeline). We want the API to provide a URL to an image on our server. This image is provided by a Model. This image could live in app/assets/images or public/images . What method will append the current host/domain to a filename, in a Rails Model?

We expected ActionController::Base.helpers.asset_url("solar.png") to work, but this returns "\\solar.png" .

We have set default_url_options to "localhost:3000"

It would be acceptable to have the model provide just the filename and the controller/json view renderer provides the URL portion via a helper. I say "acceptable", because our model is deciding what image should be returned. Sometimes that image is from the local server, sometimes it is an absolute URL from a different server. If the controller provides the URL portion, we would have to handle these two cases separately.

Fast answer:

# development.rb
config.action_controller.asset_host = "http://localhost:3000"
# production.rb
config.action_controller.asset_host = "http://yourdomain.com"

The common mistake is to set config.action_controller.default_url_options

Remember you have severals places to set your hostname:

config.action_controller.default_url_options
config.action_mailer.default_url_options
config.action_controller.asset_host
# Maybe others, I'm not sure

It's often the same value, but not everytimes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM