single table inheritance - Rails STI: transfer records from one model to another -
i have model called coupons
have 2 child models couponapplications
and approvedcoupons
. last 2 inherit coupons
via sti architecture.
now want realise following:
- a user sees couponapplications
- he clicks on approve button makes
couponapplications
approvedcoupons
i realise update type
column of coupons
record change types. however, there several concerns, hooks etc in approvedcoupons
model happening after creation not easy. in fact, want create complete new record trigger concerns, hooks etc.
so wrote consider bad:
@coupon_application = couponapplication.find(params[:id]) @approved_coupon = approvedcoupon.new # copy/paste attributes except id considered duplication @approved_coupon.attributes = @coupon_application.attributes.except("id") # set new type @approved_coupon.update_attributes(type: "advertisement") @approved_coupon.save
i hope understand want achieve. works way doubt clean code.
to summarize:
- i want change
coupon
typecouponapplication
approvedcoupon
- i still want trigger concerns, hooks etc. in
approvedcoupon
model decided create newapprovedcoupon
record instead of changing type.
is there better approach?
you add approve
method couponapplication
model this:
class couponapplication < coupon ... def approve data = attributes.except('id', 'created_at', 'updated_at') approvedcoupon.create(data.merge(type: 'advertisement')) end end
now code can simplified this:
@coupon_application = couponapplication.find(params[:id]) @approved_coupon = @coupon_application.approve
Comments
Post a Comment