0

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!

  • you should check if upon coupon deletion you also want to destroy associated objects as well: https://stackoverflow.com/questions/29560805/how-to-use-dependent-destroy-in-rails – jethroo Jan 17 '18 at 21:30

1 Answers1

0
class Coupon < ApplicationRecord
  belongs_to :user
  has_many :products, dependent: :nullify
  validates_presence_of :code, :discount_percent, :description
end
Pablo
  • 3,004
  • 1
  • 12
  • 19