Design Question - Position created from one or more Trades

I am creating a system to track equity positions ... I will enter a Trade and a Position will be created as a result ... I may have one or more Trades that make up a Position. Positions can be open or closed.

What is the best way to generate the Position object?

When a new trade is created, you need to check whether this trade is for an existing position, or whether a new position should be created.

Should I insert the code to create it manually (below) when the Trade object is created?

I would move that code into the Trade model class. The following assumes that there is no data required to create a position:

class Trade < ActiveRecord::Base

  def before_create     if !self.position       self.position = Position.create     end   end

end

In your view, make sure you have a trade_position_id field that is populated if the trade should be added to an existing position.

The before_save hook gets called after the validation, so you can be reasonably sure that the subsequent save() call will succeed. Regardless, you should wrap the @trade.save() call in your controller in a transaction so that the creation of the position gets rolled back if saving of the trade fails for some reason.

Cheers, Max