Ruby-on-rails 从 Rails 控制器访问资产路径

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7827078/
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-03 02:11:53  来源:igfitidea点击:

Access Asset Path from Rails Controller

ruby-on-railsruby-on-rails-3.1sprockets

提问by Marcel M.

I'm sharing a configuration yml file client side, that I need to also load on the server side, I've placed it inside app/assets/javascripts/configuration.yml

我正在共享一个配置 yml 文件客户端,我还需要在服务器端加载它,我将它放在 app/assets/javascripts/configuration.yml 中

I can use #{asset_path 'configuration.yml'} inside a view to get the path, but I can't inside a controller. I could access directly using "#{Rails.root}/app/assets/javascripts/configuration.yml" but when deploying the filename gets the digest string appended.

我可以在视图中使用 #{asset_path 'configuration.yml'} 来获取路径,但我不能在控制器中使用。我可以使用“#{Rails.root}/app/assets/javascripts/configuration.yml”直接访问,但是在部署文件名时会附加摘要字符串。

How can I get the same path from a controller?

如何从控制器获得相同的路径?

回答by Artem Kalinchuk

ActionController::Base.helpers.asset_path("configuration.yml")

Might also be good to put configuration.yml in a different folder to separate javascript from non-javascript files.

将 configuration.yml 放在不同的文件夹中以将 javascript 与非 javascript 文件分开也可能很好。