Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
518 views
in Technique[技术] by (71.8m points)

ruby on rails - 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

To make an assocation optional you need to make the database column nullable:

class ChangeCartsUserId < ActiveRecord::Migration[6.0]
  def change
    change_column_null :carts, :user_id, true
  end
end

And make the association optional:

class Cart < ApplicationRecord
  belongs_to :user, optional: true
  # ...
end

This simply removes the validates_presence_of validation that's added by belongs_to associations by default since Rails 5.

Another way of solving this issue is by creating "guest user" account as soon as a user adds their first item to the cart and signing the user in. You would combine this with a recurring job to clean out incomplete checkouts over time.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...