2020年12月31日星期四

Saving an object without its association

I am trying to create a cart that is able to be utilised even if the user does not login. I am currently using sessions to do this, however, the cart object will not save unless there is a user association. Whats the best way to go around this?

Here's my code

class Cart < ApplicationRecord        belongs_to :user        has_many :cart_items, dependent: :destroy        has_many :products, through: :cart_items        monetize :price_cents      end      #Application Controller      def current_customer      @user = User.find(session[:user_id]) if session[:user_id]    end      def current_shopping_cart      if login?        @cart = @user.cart      else        if session[:cart]          @cart = Cart.find(session[:cart])        else          @cart = Cart.create(delivery: "self-collection")          session[:cart] = @cart.id        end      end    end      def login?      !!current_customer    end  
https://stackoverflow.com/questions/65527033/saving-an-object-without-its-association January 01, 2021 at 11:01AM

没有评论:

发表评论