[英]Ruby on rails 5 3 model associations
I have 3 models, User, Product, Coupon. 我有3个模型,用户,产品,优惠券。
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. 我曾考虑过要在coupons_controller的破坏动作中制作product.coupon_id = nil,但我认为这是一个坏习惯。 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.
使用Postgres。
I appreciate any help! 感谢您的帮助!
class Coupon < ApplicationRecord
belongs_to :user
has_many :products, dependent: :nullify
validates_presence_of :code, :discount_percent, :description
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.