tandem tour
tandem tour

Reputation: 33

How to calculate total price in def create, API

Can you help me? I dont understand how to do it. How to calculate TOTAL PRICE when i created the room? I am dont understand how to do it right.

Here is my code:

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

Upvotes: 0

Views: 85

Answers (1)

SteveTurczyn
SteveTurczyn

Reputation: 36860

If total_price is square multiplied by price you can do that in the model.

class Room
  before_save :calculate_total

  private

  def calculate_total
    self.total_price = square * price
  end
end

Upvotes: 1

Related Questions