0

我正在使用Rails構建事件應用程序,並在我的事件和預訂模型之間添加了counter_cache關聯以捕獲每個事件所做預訂的數量。Rails - 如何使用counter_cache整合'數量'預訂並正確更新

如何在任何時候可以進行多個預訂時正確更新counter_cache?目前,每次預訂時,無論需要多少個空間(3,4,5等),counter_cache只會增加一個。這會導致預訂數量與可用空間數量(以及total_amount)不一致。

是化繁爲簡 -

def my_booking 
    event.bookings_count * booking.quantity 
end 

如果是這樣,在那裏/我怎麼叫這在我的MVC的過程?

這是我的預訂模型與set_booking方法(支付),但應該在這裏或在我的事件模型中的方法嗎?

class Booking < ActiveRecord::Base 

    belongs_to :event, counter_cache: true 
    belongs_to :user 
    before_create :set_booking_number 


    validates :quantity, presence: true, numericality: { greater_than_or_equal_to: 0 } 
    validates :total_amount, presence: true, numericality: { greater_than_or_equal_to: 0 } 

    validate(:validate_booking) 
    #validate(:validate_availability) 

    def set_booking_number 
    self.booking_number = "MAMA" + '- ' + SecureRandom.hex(4).upcase 
    end 

    def set_booking 

     if self.event.is_free? 
      self.total_amount = 0 
      save! 
     else 
      self.total_amount = event.price_pennies * self.quantity 
      begin 
      charge = Stripe::Charge.create(
       amount: total_amount, 
       currency: "gbp", 
       source: stripe_token, 
       description: "Booking created for amount #{total_amount}") 
      self.stripe_charge_id = charge.id 
      save! 
      rescue Stripe::CardError => e 
      # if this fails stripe_charge_id will be null, but in case of update we just set it to nil again 
      self.stripe_charge_id = nil 
      # we check in validatition if nil 

      end 

     end 


    end 

     def validate_booking 

     # stripe_charge_id must be set for not free events 
     unless self.event.is_free? 
      return !self.stripe_charge_id.nil? 
     end 
     end 



end 

回答

0

我認爲最好的方法是實現自己的緩存方法。

Class Event 
    def update_bookings_count(amount) 
    update_column(:bookings_count, "bookings_count + #{amount}") 
    end 
end 

預訂後成功的呼叫:

event.update_bookings_count(quantity) 

,只是使用event.bookings_count當你需要計數。

另一種選擇可能是看看這個寶石:https://github.com/magnusvk/counter_culture#totaling-instead-of-counting它似乎做你想做的。

+0

你對這個Gem是對的,但是如果我已經實現了一個遷移來併入counter_cache,那該怎麼辦。我很確定它不能被過度使用。 –

+0

您可以創建刪除舊列的新遷移。 remove_column:table_name,:column_name – user2959701