I have 3 models, User, Product, Coupon.
A User has many Products, Product belongs to User. A User has many Coupons, Coupon belongs to User.
My goal is to apply a Coupon to a Product. A Product can have one coupon and a Coupon can be applied to many Products. Currently I have the models set up like this:
#coupon.rb
class Coupon < ApplicationRecord
belongs_to :user
has_many :products
validates_presence_of :code, :discount_percent, :description
end
#user.rb
class User < ApplicationRecord
has_many :products
has_many :coupons
end
#product.rb
class Product < ApplicationRecord
belongs_to :user
has_one :coupon, dependent: :destroy
end
Currently a user can successfully create a coupon, but if I apply the coupon to the product and try to delete the coupon, it gives me a foreign key error.
I've thought about making the product.coupon_id = nil inside the destroy action of the coupons_controller but I feel that is a bad practice. Ex.)
#coupons_controller.rb
def destroy
products = Product.where(coupon_id: @coupon.id)
products.each do |product|
product.coupon_id = nil
product.save
end
@coupon.destroy
end
I think I have something wrong with my associations but can't seem to figure it out! Using Postgres.
I appreciate any help!