wcc526
wcc526

Reputation: 4095

How to get the absolute path of assets folder in rails?

I need to modify the images in the assets in the Controller.

def Test
   picpath=ActionController::Base.helpers.asset_path("images/1.jpg")
   file=open(picpath)
   ....
end

but the picpath is relative path which is ("/assets/images/1-232434.jpg") in the production environment.

I need the absolute path of the images.

The problem is the assets path is public/assets in the produciton environment,but the assets path is app/assets in the development environment.

How can I get the absolute path of the images so that I can operate the images?

Upvotes: 0

Views: 4784

Answers (2)

Richard Peck
Richard Peck

Reputation: 76774

Assets

When you use assets in ROR, you basically have a series of helpers which allow you to call resources from the asset pipeline

As stated in the comments, your asset pipeline (& accompanying helpers) have been created in such a way as to help you load the files you require, whenever you need them (whether they're in the assets/... folder, or the public/assets folder

To access assets, or images, regardless of which folder they're in, or if they've been fingerprinted, you'll be able to use the likes of asset_path or image_path to load them successfully:

asset_path "path/to/asset"

--

Images

As stated in the other answer, you'll be best using something like Paperclip to help manage your image uploads.

If you're allowing users to upload images, a system such as Paperclip will allow you to organize their uploads into a database, and then call the image through ActiveRecord:

#app/controllers/images_controller.rb
Class ImagesController < ApplicationController
   def index
       @images = Image.all
   end
end

#app/views/images/index.html.erb
<% @images.each do |image| %>
   <%= image_tag image.attachment.url #=> reference to Paperclip %>
<% end %>

Upvotes: 1

lucius
lucius

Reputation: 61

The asset folder depends on the environment as you said so you get the right folder in both cases.

If you have pictures as attachments, for example, I suggest something like paperclip. If you have to upload pictures you can use for example carrierwave.

If you want you custom solution I would store the pictures in a subfolder in the public folder like public/custompics. In this case you can access a picture at the relative path /custompics/1.jpg

Upvotes: 1

Related Questions