marcamillion
marcamillion

Reputation: 33755

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

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.

Upvotes: 1

Views: 315

Answers (2)

Ursus
Ursus

Reputation: 30056

Try assign_attributes, it accepts an hash as parameter and don't hit the database, it works just on the object

@port_stock.assign_attributes(current_price: stock.price)

Obviously, if you want just update one field, @Sergio's answer is better and simpler

Upvotes: 8

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230286

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))

Upvotes: 9

Related Questions