Home>

Ruby on rails I am a beginner.
We are currently constructing an EC site, and the one that stumbles is the process of "putting in the cart" using the session function.
Referenced site "https://qiita.com/kenzo-ta/items/b45994c5f3fdd87b6c50"

I checked the association many times, but the error persisted.
Is it due to another part?
(Postscript) → Isn't it an error because "current_cart" is empty?
→ Since "session[:cart_id" does not contain anything, "current_cart" becomes empty and an error occurs. (hypothesis)
→If the current_cart action does not have [:cart_id], it should be written so as to "create"? ?

NoMethodError (undefined method `cart_items' for nil:NilClass):
app/controllers/carts_controller.rb:32:in `set_line_item'
Applicable source code
(app/vies/products/show.html.erb)

    <%= form_for(:session, url: carts_path) do |f|%>
    <%= f.label :quantity, "quantity"%>
    <%= f.select :quantity, [1,2,3,4,5,6,7,8,9,10]%>
    <%= f.submit "Add to cart", class:"btn cart_btn" %>
    <% end %>
(App/controllers/carts_controller)
class CartsController</pre>
<pre><code>(App/controllers/application_controller)
private
def current_cart
      if session[:cart_id]
        current_cart = Cart.find_by(id: session[:cart_id])
        current_cart = Cart.create unless current_cart
        session[:cart_id] = current_cart.id
        current_cart
      end
end
(App/models/product.rb)
class Product
(App/models/cart_item.rb)
class CartItem
(App/models/cart.rb)
class Cart
What I tried

I thought it might be an association issue, and reconfirmed has_many and belong_to.

Supplemental information (FW/tool ​​version, etc.)

ruby 2.6.6
rails'~>5.2.4','>= 5.2.4.3'

  • Answer # 1

    undefined method `cart_items' for nil:NilClass

    This error is caused by calling cart_items from nil.

    So current_cart feels nil

    (App/controllers/application_controller)
    private
    def current_cart
          if session[:cart_id]
            current_cart = Cart.find_by(id: session[:cart_id])
            current_cart = Cart.create unless current_cart
            session[:cart_id] = current_cart.id
            current_cart
          end
    end

    If session[:cart_id] does not exist in this part, it will work if you create a new one.