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_at
tosale_start_time
- an attribute of the modelSale
- which I can later use to trigger mark-downs, for example,@sale_start_time+5day
. In theSale
model: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).Product
does toggleproduct_on_sale: false
toproduct_on_sale: true
(which, practically speaking, removes it from product inventory). TheSale
update of the attribute doesn't work. It 'raises''id'={:id=>nil}
I'd userSale.find_by(@product_id)...
however,product_id
may 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_create
callback.In the
Sale
model add this:Edit by OP: This works IF the controller method
def create
defines sale as@sale = Sale.create(sale_params)
'create' sets thesale id
. I was using@sale = Sale.new(sale_params)
which does not set thesale id
until the transaction is committed.