逻辑陈述/谜题.如何只选择忠诚度卡的价格,而忽略其他价格



我已经想了一段时间了,但我没有主意。

上下文

当一个人租了几个晚上的房间时,我正在计算总房价。房间价格对于日期是唯一的,除非特定房间价格设置了忠诚度_卡片

在后面的场景中,一个日期可能有两个不同的价格:

没有忠诚卡的房间价格
  • 忠诚的房间卡片
  • 如果预订包括忠诚度卡,则预订应仅包括带有忠诚度卡的房间价格。

    问题

    我目前的设置适用于没有忠诚度卡的用户。

    然而,对于持有忠诚卡的用户(其中reservation.redulty_card与room_price的忠诚度_card匹配(,该方法将约会的价格、有忠诚卡的room_prince和没有忠诚卡的房价相加。

    在这种情况下,我怎么能只使用room_price和忠诚度_card?

    def total_room_price(reservation)
    sum_room = 0
    price_list = []
    (reservation.arrival...reservation.departure).each do |date|
    reservation.room.room_category.room_prices.each do |price|
    if ((price.start_date..price.end_date).include? date) && (price.loyalty_card.nil? || price.loyalty_card == reservation.loyalty_card)
    sum_room += price.price
    end
    end
    end
    sum_room
    end
    

    型号

    class RoomPrice < ApplicationRecord
    belongs_to :room_category
    belongs_to :card, optional: true
    end
    class Card < ApplicationRecord
    belongs_to :hotel
    has_many :discounts
    has_many :room_prices
    has_many :reservations
    end
    class Reservation < ApplicationRecord
    belongs_to :discount, optional: true
    belongs_to :card, optional: true
    belongs_to :hotel
    belongs_to :room
    end
    

    使用两步方法解决了它,但它确实很全面。如果有人有更好的解决方案,我会洗耳恭听。

    def total_room_price(reservation)
    sum_room = 0
    dates = reservation.arrival...reservation.departure
    dates.each do |date|
    #arrangement card
    reservation.room.room_category.room_prices.each do |price|
    if ((price.start_date...price.end_date).include? date) && (price.card == reservation.card)
    sum_room += price.price
    dates = dates.without(date)
    end
    end
    end
    #arrangement no card
    dates.each do |arr_no_card_date|
    reservation.room.room_category.room_prices.each do |arr_price|
    if ((arr_price.start_date...arr_price.end_date).include? arr_no_card_date) && (arr_price.card.nil?)
    sum_room += arr_price.price
    dates = dates.without(arr_no_card_date)
    end
    end
    end
    sum_room
    end
    

    最新更新