如何获取Rails应用程序的根目录路径?


当前回答

只需编写Rails.root 并附加任何 Rails.root。Join (*%w(应用程序资产)).to_s

其他回答

在Rails 3及更新版本中:

Rails.root

它返回一个Pathname对象。如果你想要一个字符串,你必须添加。to_s。如果你想在你的Rails应用程序中使用另一个路径,你可以像这样使用join:

Rails.root.join('app', 'assets', 'images', 'logo.png')

在Rails 2中,你可以使用RAILS_ROOT常量,它是一个字符串。

除了所有其他正确答案,因为Rails。root是一个Pathname对象,这行不通:

Rails.root + '/app/assets/...'

您可以使用join之类的东西

Rails.root.join('app', 'assets')

如果你想要一个字符串,使用这个:

Rails.root.join('app', 'assets').to_s

您可以通过变量RAILS_ROOT访问rails应用程序路径。

例如:

render :file => "#{RAILS_ROOT}/public/layouts/mylayout.html.erb"
module Rails
  def self.root
    File.expand_path("..", __dir__)
  end
end

来源: https://github.com/rails/rails/blob/5259062868dcf10fbcf735d6520e6a14e15fdcdb/actionmailer/test/abstract_unit.rb#L12

你可以使用:

Rails.root

但要加入您可以使用的资产:

Rails.root.join(*%w( app assets))

希望这能帮到你。