简体   繁体   English

Ruby on Rails无法加载关注模块

[英]Ruby on Rails cannot load concern module

I have initialized a module in the folder "concerns" located in: appname/app/models/concerns 我已经在以下文件夹中的“关注点”中初始化了一个模块: appname / app / models / concerns

called current_cart.rb 叫做current_cart.rb

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

i'm including this in my controller line_item_controllers: 我将其包含在我的控制器line_item_controllers中:

appname/app/controllers/line_items_controller.rb appname / app / controllers / line_items_controller.rb

class LineItemsController < ApplicationController
  include CurrentCart

but it produces this error when i try to execute on my browser: 但是当我尝试在浏览器上执行时会产生此错误:

uninitialized constant LineItemsController::CurrentCart

app/controllers/line_items_controller.rb:2:in `<class:LineItemsController>'
app/controllers/line_items_controller.rb:1:in `<top (required)>'

Nothing seems to be wrong here, if we are talking about Rails 4 - it should work out of the box. 如果我们在谈论Rails 4,那么这里似乎没有什么错-它应该开箱即用。

However, what you are doing is a slight misuse of what concerns are for. 但是,您正在做的是对所关注问题的轻微滥用。 And you are defining models/concerns , where you should put this one in controllers/concerns (for readability's sake). 并且您正在定义models/concerns ,应该将其放在controllers/concerns (出于可读性controllers/concerns )。

For this case, controller filters are more suitable. 对于这种情况, 控制器过滤器更为合适。

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

Based on the code, I'm assuming you are following along with the book, "Agile Web Development with Rails." 根据代码,我假设您正在跟着《用Rails进行敏捷Web开发》这本书。

I would recommend just moving your code from: 我建议您将代码从以下位置移开:

appname/app/models/concerns/current_cart.rb

to: 至:

appname/app/controllers/concerns/current_cart.rb

This would allow you to most easily follow the example in the book. 这将使您最轻松地遵循本书中的示例。

Was having the same problem. 有同样的问题。 For me it was a simple bug. 对我来说,这是一个简单的错误。 It couldn't read LineItemsController::CurrentCart because when I created current_cart.rb it was saved with an aditional white space at the end (after .rb), .eg current_cart.rb(space) 它无法读取LineItemsController::CurrentCart因为当我创建current_cart.rb它的末尾带有附加空白(.rb之后),例如._current_cart.rb current_cart.rb(space)

So after deleting the white extra space it all worked out well. 因此,删除白色多余的空格后,一切都很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM