简体   繁体   中英

Ruby on Rails cannot load concern module

I have initialized a module in the folder "concerns" located in: appname/app/models/concerns

called 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:

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.

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).

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."

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)

So after deleting the white extra space it all worked out well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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