Ruby 在 Rails 上:使用模块

Ruby on Rails: Using Modules

我对 Rails 上的 Ruby 比较陌生,但我几乎完成了 Lynda 的在线课程。我停留在 14-5 "Using the positionMove module"。教程在Rails 3,而我的版本是Rails 4。我有解决方案代码,但它对我不起作用。我已将我的文件 position_mover.rb 放在 lib 目录中。然后在我的主题模型中,我需要并包含这样的模块:

require 'lib/position_mover'
class Subject < ActiveRecord::Base

  include PositionMover
  ...
end

我和老师一样在Subject controller中使用了这个模型中的方法。但是,当我在主题索引页面上转到 运行 我的应用程序时,出现错误:

cannot load such file -- lib/position_mover

app/models/page.rb:1:in `<top (required)>'
app/views/subjects/list.html.erb:23:in `block in_app_views_subjects_list_html_erb__420960863_60005508'
app/views/subjects/list.html.erb:18:in `_app_views_subjects_list_html_erb__420960863_60005508'
app/controllers/subjects_controller.rb:9:in `index'

我尝试了很多在网上找到的不同方法,例如将其添加到 class 定义 (Ruby on Rails 4.0 - Loading and using a module) 或将其移动到不同的目录并指定路径。如何在 Rails 4 中获得相同的结果?我究竟做错了什么?非常感谢任何帮助。

require "#{Rails.root}/lib/position_mover" 

require_relative 'lib/position_mover'

您还可以自动加载 lib 文件。

config/application.rb中:

config.autoload_paths << Rails.root.join('lib')