레일스를 사용하여 이벤트 앱을 만들고 각 이벤트에 예약 수를 캡처하기 위해 내 이벤트와 예약 모델간에 counter_cache 연결을 추가했습니다. .레일스 - counter_cache를 사용하여 '수량'예약을 통합하고 올바르게 업데이트하는 방법
한 번에 둘 이상의 예약을 할 수있는 경우 counter_cache를 올바르게 업데이트하려면 어떻게해야합니까? 현재 예약이 이루어질 때마다 이벤트에 필요한 공간의 수 (3,4,5 등)에 관계없이 counter_cache는 하나씩 증가합니다. 이것은 이용 가능한 공간의 수 (및 total_amount)에 대한 예약 수의 부정확성을 야기한다. 그래서, 어디에/어떻게 내 MVC 과정에서이 전화 않으면
def my_booking
event.bookings_count * booking.quantity
end
-
은은 간단하다?
결제 방법으로 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
당신은 그 보석에 대해 옳았습니다. 그러나 counter_cache를 통합하기 위해 이미 마이 그 레이션을 구현했다면 어떻게 될까요? 나는 그것이 overidden 될 수 없다라고 꽤 확신한다. –
이전 열을 삭제하는 새 마이그레이션을 만들 수 있습니다. remove_column : table_name, : column_name – user2959701