[英]Ruby on Rails cannot load concern module
我已經在以下文件夾中的“關注點”中初始化了一個模塊: appname / app / models / concerns
叫做current_cart.rb
appname / app / models / concerns / current_cart.rb
module CurrentCart
extend ActiveSupport::Concern
private
def set_cart
@cart = Cart.find(session[:cart_id])
rescue ActiveRecord::RecordNotFound
@cart = Cart.create
session[:cart_id] = @cart.id
end
end
我將其包含在我的控制器line_item_controllers中:
appname / app / controllers / line_items_controller.rb
class LineItemsController < ApplicationController
include CurrentCart
但是當我嘗試在瀏覽器上執行時會產生此錯誤:
uninitialized constant LineItemsController::CurrentCart
app/controllers/line_items_controller.rb:2:in `<class:LineItemsController>'
app/controllers/line_items_controller.rb:1:in `<top (required)>'
如果我們在談論Rails 4,那么這里似乎沒有什么錯-它應該開箱即用。
但是,您正在做的是對所關注問題的輕微濫用。 並且您正在定義models/concerns
,應該將其放在controllers/concerns
(出於可讀性controllers/concerns
)。
對於這種情況, 控制器過濾器更為合適。
class LineItemsController < ApplicationController
before_action :set_cart
private
def set_cart
@cart = Cart.find(session[:cart_id])
rescue ActiveRecord::RecordNotFound
@cart = Cart.create
session[:cart_id] = @cart.id
end
end
根據代碼,我假設您正在跟着《用Rails進行敏捷Web開發》這本書。
我建議您將代碼從以下位置移開:
appname/app/models/concerns/current_cart.rb
至:
appname/app/controllers/concerns/current_cart.rb
這將使您最輕松地遵循本書中的示例。
有同樣的問題。 對我來說,這是一個簡單的錯誤。 它無法讀取LineItemsController::CurrentCart
因為當我創建current_cart.rb
它的末尾帶有附加空白(.rb之后),例如._current_cart.rb current_cart.rb(space)
因此,刪除白色多余的空格后,一切都很好。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.