这是我的代码:
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
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
答案 0 :(得分:1)
如果total_price
square
乘以price
,您可以在模型中执行此操作。
class Room
before_save :calculate_total
private
def calculate_total
self.total_price = square * price
end
end