0

I have a System class with an attr called price and a Subsystem class (belongs_to :system) with also this price attr.

The problem is in my model, because I have two different ways of treating the system.price

1) The system has at least one subsystem (!system.subsystems.empty?): I want the price to be the sum of all it's subsystems prices. In that case, my model has it's method price with a loop to sum the subsystems prices.

2) The system doesn't have ANY subsystem (system.subsystems.empty?): The price is simply an input field which it's filled in a form.

The trouble i'm facing is how to 'choose' which way to follow...

Can anyone help me? Thks a lot in advance!!!

4

2 回答 2

1

您始终可以将系统的价格存储在其他地方,并在必要时选择使用它:

class System

  has_many :subsystems

  def price
    subsystems.empty? system_price : subsystems.sum('price')
  end

  def system_price
    # maybe an active record attribute, this method might not exist
    25.00
  end

end
于 2013-08-30T15:24:32.167 回答
0

您可以简单地覆盖模型中的价格方法:

def price
  if subsystems.empty? 
    self.attributes["price"] 
  else
    subsystems.map(&:price).sum
end
于 2013-08-30T15:25:04.580 回答