I am building an e-commerce app. I want to assign created_at to an attribute.
Stale Product inventory is 'sent' / 'submitted' to the SaleController, creating a product on sale.
- I am trying to assign the time
created_attosale_start_time- an attribute of the modelSale- which I can later use to trigger mark-downs, for example,@sale_start_time+5day. In theSalemodel:def sale_start_time @sale.created_at end
That does not work, nor does @sale_start_time = @sale.created_at -- even though in a view, for example sales#show, @sale.created_at returns the created_at time.
I also tried placing it in a Sale model
after commit(although I can't determine if two attributes can be changed in a single after commit).Productdoes toggleproduct_on_sale: falsetoproduct_on_sale: true(which, practically speaking, removes it from product inventory). TheSaleupdate of the attribute doesn't work. It 'raises''id'={:id=>nil}I'd userSale.find_by(@product_id)...however,product_idmay not equalsale_id.def update_status Product.find_by(@product_id).toggle!(:product_on_sale) Sale.find(id: @id).update(sale_start_time: @sale.created_at) end
Thank you in advance for your help.
If I understood your question correctly, you can assign it in a
after_createcallback.In the
Salemodel add this:Edit by OP: This works IF the controller method
def createdefines sale as@sale = Sale.create(sale_params)'create' sets thesale id. I was using@sale = Sale.new(sale_params)which does not set thesale iduntil the transaction is committed.