1

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)>'
3
  • 1
    Is app/models/concerns in your load_paths? Commented Sep 30, 2014 at 9:59
  • 1
    Which rails version you are using? Commented Sep 30, 2014 at 10:01
  • i'm using a version of rails 4.0 Commented Sep 30, 2014 at 10:14

3 Answers 3

3

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
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

1

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.

1 Comment

Mine was similar, I forgot to put .rb at the end of the filename, seeing this helped me find that when I was looking for a space at the end so kudos

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.