【问题标题】:Cannot use gem in rails controller无法在 Rails 控制器中使用 gem
【发布时间】:2014-06-22 20:58:31
【问题描述】:

我是一个 Rails 菜鸟,所以任何帮助都将不胜感激。

我已通过以下方式安装了 soundcloud gem:

$  gem install soundcloud

然后我将 gem 添加到我的 Gemfile 中,并运行 rails bundle install 以确保它包含在我的项目中:

$  bundle install

这会输出我项目中所有包含的 gem 的列表。接近尾声的项目之一是 soundcloud gem:

$  bundle install
...
Using sdoc 0.4.0
Using soundcloud 0.3.2
Using spring 1.1.2
...
Your bundle is complete!
Use `bundle show [gemname]` to see where a bundled gem is installed.

现在,当我在我的应用程序目录中运行 rails 控制台时,我可以按预期访问 soundcloud 模块:

$ rails console
Loading development environment (Rails 4.1.0)
2.1.1 :001 > SoundCloud
 => SoundCloud
2.1.1 :002 > client = SoundCloud.new(:client_id => 'b2dab282f8bb29467dcb4f5b27f7c075')
 => #<SoundCloud::Client:0x8972f40 ... (successful results here)

但是当我尝试在控制器或视图中使用 soundcloud 模块时,我得到一个错误的页面:

uninitialized constant SlideshowController::SoundCloud

这是我尝试使用 soundcloud 模块的代码:

helper_method :sc_get_src

def sc_get_src
    @sc_client ||= SoundCloud.new(:client_id => 'b2dab282f8bb29467dcb4f5b27f7c075')
    sound = @sc_client.get('/resolve', :url => @slideshow.sound)
    return sound.uri
end

在文档页面here 示例中的第一行是:

require 'soundcloud'

但是,如果我在使用 soundcloud 模块(在控制器、模型、视图等中)之前添加它,则会引发此错误:

cannot load such file -- soundcloud

请帮忙。是否需要采取其他步骤才能将模块包含在我的应用程序中?

提前谢谢你。

【问题讨论】:

  • 我知道您已将 gem 添加到 gemfile 中吗?
  • 是的,我会更新问题以包含此信息。
  • 您可以尝试使用 -e production 运行控制台,以查看问题是否在答案中所述的整个环境中持续存在?

标签: ruby-on-rails-4 soundcloud ruby-on-rails-plugins


【解决方案1】:

这些问题通常可以通过重启您的 rails 服务器来解决。例如。对于乘客:

$ touch tmp/restart.txt

原因是,gem 依赖项仅在应用的启动阶段加载

【讨论】:

  • 对该主题的另一条评论。当控制台中的某些内容可以正常工作但 web 应用程序中无法正常工作时,需要重新启动始终是一个很好的提示。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多