How do I update an object that hasn't been saved without saving it?

  • A+
Category:Languages

So I am doing this:

@portfolio = current_user.portfolio @port_stock = PortStock.new(port_stock_params) stock = Stock.find(port_stock_params[:stock_id]) @port_stock.update!(current_price: stock.price)  respond_to do |format|   if @port_stock.save 

The issue I am having is that when I call .update! on @port_stock it actually saves the record before @port_stock.save later.

So my callbacks are being executed twice, which is messing up stuff in my DB.

So how do I update the new instance of @port_stock.current_price without actually saving the @port_stock object before I call it explicitly?

Thanks.


If you're only updating one attribute, you could just use the setter:

@port_stock.current_price = stock.price 

Or you could do:

stock = Stock.find(port_stock_params[:stock_id]) @port_stock = PortStock.new(port_stock_params.merge(current_price: stock.price)) 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: