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:

  1. a user sees couponapplications
  2. he clicks on approve button makes couponapplications approvedcoupons

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 coupontype couponapplication approvedcoupon
  • i still want trigger concerns, hooks etc. in approvedcoupon model decided create new approvedcoupon 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

Popular posts from this blog

html - Firefox flex bug applied to buttons? -

html - Missing border-right in select on Firefox -

c# - two queries in same method -