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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…