Ajey
Ajey

Reputation: 8202

Rails saving data to model that has multiple has_many

So I have a product model that looks like

belongs_to :seller
has_many :coupons

And coupon model that looks like

belongs_to :seller
belongs_to :product

And in my Products controller I use

@seller = current_user
@coupon = @seller.coupons.create(params[:coupon])

to create the coupons for the seller

While the coupon is being created, I need to associate it with the product too, i.e When a new coupon is created it should be saved for the seller AS WELL AS for the product.

Upvotes: 0

Views: 57

Answers (2)

zwippie
zwippie

Reputation: 15515

Your code should work if params[:coupon] contains a product_id.

Upvotes: 1

Adeptus
Adeptus

Reputation: 683

you can create like:

@coupon = @seller.coupons.create(params[:coupon], product_id: @product.id)

Upvotes: 0

Related Questions