如何计算def create,API中的总价格

时间:2017-12-15 14:06:56

标签: ruby-on-rails

你能帮帮我吗?我不明白该怎么做。 当我创建房间时如何计算总价? 我不明白该怎么做。

这是我的代码:

room_controller.rb

def create
  parameters = room_params.to_hash
  parameters[:created_by] = @current_user.id
  parameters[:account_id] = @current_user.account_id
  @room = @section.rooms.create!(parameters)

  update_room(@room, params)
end
 ...
def update
  params = room_params.to_hash
  update_room(@room, params)
  json_response(@room)
end

 def update_room(room, json)
return unless room
unless json.key?('total_price')
  if json.key?('price') || json.key?('square')
    square = json.key?('square') ? json['square'].to_f : room.square
    price = json.key?('price') ? json['price'].to_f : room.price
    json['total_price'] = price * square
  end
end
unless json.key?('price')
  if json.key?('total_price') || json.key?('square')
    square = json.key?('square') ? json['square'].to_f : room.square
    total_price = json.key?('total_price') ? json['total_price'].to_f : room.total_price
    json['price'] = total_price / square
  end
end
 room.update(json)
end

def room_params
 params.permit(
   :level, :square, :total_price, :price, :number, :room_type,
   :plan_image, :plan_coordinate, :view_image, :interior_image,
   :rooms_count, :status, :marked
 )
end

schema.rb

create_table "rooms", force: :cascade do |t| 
 ...
 t.float "square", default: 0.0
 t.float "price", default: 0.0
 t.float "total_price", default: 0.0

1 个答案:

答案 0 :(得分:1)

如果total_price square乘以price,您可以在模型中执行此操作。

class Room
  before_save :calculate_total

  private

  def calculate_total
    self.total_price = square * price
  end
end