やりたいこと
has_manyのリレーションを、has_oneに変更したいんですが、
コードをどう修正すればよろしいかご教授お願いします。
現状は、1オーダーで複数のクーポンが使用できる感じだったのですが、
1オーダーで1クーポンしか使わないのでそれをhas_oneに修正したい意図があります。
引っ掛かってる部分は、Railsに疎い為中間テーブルを挟んでる関係で、
has_oneとbelong_toの関連付けをどうしたらいいのか分からなくてご質問しようと思いました。
対象モデル
Orderモデル
id | price |
---|---|
1 | 2000 |
Couponモデル
id | name | code |
---|---|---|
1 | クーポンA | クーポンコード |
OrderCoupon モデル
id | coupon_id | order_id |
---|---|---|
1 | 1 | 1 |
対象コード
Ruby
1class Order < ApplicationRecord 2 has_many :order_coupons 3 has_many :coupons, through: :order_coupons 4end
Ruby
1class Coupon < ApplicationRecord 2 has_many :order_coupons 3 has_many :orders, through: :order_coupons 4end
Ruby
1class OrderCoupon < ApplicationRecord 2 belongs_to :coupon 3 belongs_to :order 4end
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。