我正在將Rails 2應用程序遷移到Rails 3,並遇到一個主要問題。我有一個被稱爲在我application.html.erb稱爲check_author_role
方法,它是扔Rails 3:application.rb不加載?
undefined local variable or method `check_author_role'
的check_author_role方法是在一個名爲LIB/authenticated_system.rb定義。
我瞭解到,Rails 3中不再自動加載的lib/
目錄,所以我增加了以下行config/application.rb
:
config.autoload_paths += %W(#{config.root}/lib)
config.autoload_paths += Dir["#{config.root}/lib/**/"]
我認爲這會做到這一點。不過,我仍然收到錯誤。這意味着,執行下列操作之一是怎麼回事:
- 的config/application.rb中沒有被正確加載
- 我的自動加載語法是錯誤的
- 我定義在一個過時的方式 方法
- 我打電話我已經在這幾個小時,現在已經被廢棄的方法
的方法,不能使頭或它的尾巴。 Rails 3更新之前一切都很好。任何人都有一些建議?
這裏是lib/authenticated_system.rb
樣子:
module AuthenticatedSystem
protected
def check_author_role
check_role('author')
end
def check_role(role)
if logged_in? && @current_user.has_role?(role)
true
else
access_denied
end
end
end
而這裏的app/layout/application.html.erb
樣子:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head profile="http://www.w3.org/2005/10/profile">
...
</head>
<body>
...
<% if check_author_role %>
...
<% end %>
...
</body>
</html>
最後,這裏的config/application.rb
require File.expand_path('../boot', __FILE__)
require 'rails/all'
Bundler.require(:default, Rails.env) if defined?(Bundler)
module MyApp
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Custom directories with classes and modules you want to be autoloadable.
# config.autoload_paths += %W(#{config.root}/extras)
config.autoload_paths += %W(#{config.root}/lib)
config.autoload_paths += Dir["#{config.root}/lib/**/"]
...
end
end
我承認我很模糊關於輔助方法如何工作,尤其是在Rails中這是我注意到的。
在lib/authenticated_system.rb
:
# Inclusion hook to make methods
# available as ActionView helper methods.
def self.included(base)
base.send :helper_method, :current_user, :logged_in?, :check_role, :check_administrator_role, :check_author_role, :has_role, :has_administrator_role, :has_author_role
end
我會誠實地說我真的不知道是什麼base.send
是怎麼一回事。
在app/controllers/application.rb
我有以下幾點:
class ApplicationController < ActionController::Base
helper :all # include all helpers, all the time
include AuthenticatedSystem
再次,我怕我不完全理解的正是這種代碼是做什麼。
奇怪的是我注意到我在同一個目錄中也有一個非常相似的文件:app/controllers/application_controller.rb
。它幾乎是空的,只有三條線。
class ApplicationController < ActionController::Base
protect_from_forgery
end
我的假設:app/controllers/application_controller.rb
是新的Rails 3檔,而app/controllers/application.rb
我的舊代碼從我的Rails 2個網站。我會測試這個。
並重新啓動後,編輯服務器? – rubyprince 2011-06-06 15:07:53
我有一個運行「rails s」的終端窗口,我點擊CTRL + C停止它,然後再次輸入「rails s」命令。這是足夠的,還是有另一個重新開始,我是愚蠢的和遺忘的方面? – isthmus 2011-06-06 15:24:13
您的模塊(或類)是否在lib/authenticated_system.rb中正確命名?含義:它是否定義了「模塊AuthenticaedSystem」? – theIV 2011-06-06 15:42:26