I am trying to choose an image randomly from a sub directory inside my /app/assets/images directory using the Dir.glob() command, and then display it with an image_tag. Somehow I can’t get it to work.
Here’s my code:
- @badges = Dir.glob("app/assets/images/badges/*")
= image_tag @badges.sample
Which produces the following error:
ActionController::RoutingError (No route matches [GET] "/assets/app/assets/images/badges/produce.png"):
As you can see the asset pipeline is inserting an “/assets” in front of the directory. Alright Rails, I’ll meet you halfway here. So next I try removing /app/assets from the query path to make it work and get the following result:
- @badges = Dir.glob("images/badges/*")
= image_tag @badges.sample
ActionController::RoutingError (No route matches [GET] "/assets"):
What am I doing wrong here? Thanks in advance for your help!
Dir.globis going to return images with a relative path, so yourproduce.pngfile will be returned as:However, you need to pass only the
badges/produce.pngpart toimage_tag. You need to remove the stuff before this:You may want to stick this in a helper instead:
and then in your view: