如何从模型方法访问公共文件夹?

4
我希望在模型中做类似于这样的事情,使用公共文件夹作为文件数据库。
all_images = []
(1..100).each do |image_number|
   if File.exists?("/img/#{image_number}.jpg")
      # add image path to the list
   end
end

有没有办法让Rails以这种方式“看到”public目录中的文件?

如果您正在使用Rails 4,则需要查看http://guides.rubyonrails.org/asset_pipeline.html。 - lurker
你的问题已经在SO上被问过很多次了,请下次使用搜索功能。 - Rustam Gasanov
Rails.root可能对你有用:https://dev59.com/ZG865IYBdhLWcg3wnf9t#3724527 - rogerdpack
4个回答

5
如果您使用资源管道并且想要检查资产是否存在,请在资产文件夹中查找:
 all_images = 1.upto(100).map do |image_number|
   path = Rails.root.join("assets/images/#{image_number}.jpg")
   path if File.exists?(path)
 end.compact

如果您的资源位于public文件夹中,这种做法并不推荐(因为有各种原因),除非您使用Rails < 3版本或者自己构建了一些资源管理扩展。如果是这样,您可以在那里查找它:

 all_images = 1.upto(100).map do |image_number|
   path = Rails.root.join("public/img/#{image_number}.jpg")
   path if File.exists?(path)
 end.compact

0

检查文件是否存在,您可以使用以下代码:

if File.exists?("#{Rails.public_path}/img/#{image_number}.jpg")

这将适用于任何文件系统:

if File.exists?(File.join(Rails.public_path, "img", "#{image_number}.jpg"))

要获取所有现有文件,您可以链接 #map#select

all_images = (1..100).
  map { |i| File.join(Rails.public_path, "img", "#{i}.jpg") }.
  select{ |path| File.exists? path }

0

您可以使用Rails.root.join('public', 'img', '1.jpg')来访问它。


0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接