single table inheritance - Rails STI: transfer records from one model to another -
i have model called coupons have 2 child models couponapplicationsand approvedcoupons. last 2 inherit couponsvia sti architecture.
now want realise following:
- a user sees couponapplications
- he clicks on approve button makes
couponapplicationsapprovedcoupons
i realise update typecolumn of couponsrecord 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
coupontypecouponapplicationapprovedcoupon - i still want trigger concerns, hooks etc. in
approvedcouponmodel decided create newapprovedcouponrecord 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