Ruby-on-rails Rails:文件路径

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13147277/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 20:57:13  来源:igfitidea点击:

Rails: path of file

ruby-on-railsrubyruby-on-rails-3

提问by socksocket

I have inside appa directory called csvand inside this dir I have a file called names.csvI want to use File.read(path:string)function to read the file.
what is the relative path to the file?

我在app一个名为的目录中csv,在这个目录中我有一个名为names.csv我想使用File.read(path:string)函数读取文件的文件。
文件的相对路径是什么?

回答by tamersalama

file = File.join(Rails.root, 'app', 'csv', 'names.csv')
File.read(file)

回答by user566245

You should do: Rails.root.join "app", "csv", "names.csv"

你应该做: Rails.root.join "app", "csv", "names.csv"

Rails.root returns a PathName object. PathName has a joinmethod which takes any number of arguments and appends it to the pathname to create the new path.

Rails.root 返回一个 PathName 对象。PathName 有一个join方法,它接受任意数量的参数并将其附加到路径名以创建新路径。

Read on PathName#join here:

在此处阅读 PathName#join:

http://www.ruby-doc.org/stdlib-1.9.3/libdoc/pathname/rdoc/Pathname.html#method-i-join

http://www.ruby-doc.org/stdlib-1.9.3/libdoc/pathname/rdoc/Pathname.html#method-i-join

回答by Laas

Rails.rootpoints to the top folder of your rails project, so the path would be:

Rails.root指向 Rails 项目的顶部文件夹,因此路径为:

File.read(File.join(Rails.root, 'app','csv','names.csv'))

回答by Atchyut Nagabhairava

Thanks for above answers, It also worked this way for me:

感谢上述答案,它也对我有用:

"#{Rails.root}/public/spreadsheets/file_name.xlsx"