В Rails применить приращение после завершения транзакции - PullRequest
0 голосов
/ 16 мая 2018

Пользователи совершают транзакции, возможно, с кодом купона, и в конце статус меняется, корзина помечается как завершенная, и отправляется почтовая рассылка.То, что я пытаюсь сделать, это также обновить код купона, используемый с постепенным изменением.Сейчас модель заказа транзакции имеет следующий вид:

class TbCommerce::Order < ActiveRecord::Base
 self.table_name = 'tb_commerce_orders'
 scope :search, ->(term){ where('name LIKE ?', "%#{term}%") }

 belongs_to :cart, :inverse_of => :order, :foreign_key => :tb_commerce_cart_id
 has_many :transactions, :inverse_of => :order, :foreign_key => :tb_commerce_order_id
 has_one :captured_transaction, ->{ captured }, :class_name => 'TbCommerce::Transaction', :foreign_key => :tb_commerce_order_id

 validates_presence_of :cart, :name, :address, :city, :state, :postal, :country
 validates_uniqueness_of :cart
 validates_length_of :address, :maximum => 30
 validates :email, :format => {:with => Authlogic::Regex.email, :message => 'should look like an email address.'}
 before_create :set_invoice_number

 define_callbacks :capture
 set_callback :capture, :after, :after_capture

 def description
  return cart.description
end

module Status
OPEN = 'open'
PLACED = 'placed'
SHIPPED = 'shipped'
REFUNDED = 'refunded'
REMOVED = 'deleted'
end

def full_name
 return name
end

def full_address
 return "#{address}, #{city} #{state}, #{postal}, #{country}"
end

private

def set_invoice_number
  new_invoice_number = TbCommerce::Order.maximum(:invoice_number) || 1000000
loop do
  new_invoice_number += 1
  break unless TbCommerce::Order.exists?(:invoice_number => new_invoice_number)
end
self.invoice_number = new_invoice_number
end

def after_capture
  update_attribute(:status, Status::PLACED)
  cart.update_attribute(:is_completed, true)
  coupon.update(:used => used + 1)
  TbCommerce::OrderMailer.order_placed(self).deliver_later
  TbCommerce::OrderMailer.order_confirmation(self).deliver_later
  begin
    TbCommerce.after_capture.call(self)
  rescue e
    logger.error "Failed to run the after_capture hook with message: #{e}"
  end
   return true
  end

 end

Это строка в after_capture = coupon.update (: used => used + 1).Это на самом деле не увеличивается.Я также попытался сделать @ coupon.update (: used => used + 1) и TbCommerce :: Coupon.increment_used (self), а затем в модели:

class TbCommerce::Coupon < ActiveRecord::Base
   scope :ordered, ->{ order('created_at desc') }
   scope :search, ->(term){ where('code LIKE ?', "%#{term}%") }

   validates :code, :presence => true, :uniqueness => true
   attr_accessor :skip_api_post

 def increment_used
  update(:used => used + 1)
end

end

Нет сбоев, но не увеличивается.

Редактировать:

Проверка кода в моем шоу, который имеет следующее:

<% @coupons.each do |coupon| %>
 <%= coupon.code %>
 <%= coupon.used %>
<% end %>

Дополнительное редактирование: я пробовал все следующие, и ни один из них не работает илифактически вызвать привязку pry:

increment_coupon_used!
binding.pry
update(:used => used + 1)
binding.pry
update_attribute(:used => used + 1)
binding.pry
update_attribute(used: @coupon.used + 1)
binding.pry
TbCommerce::Coupon.increment!(:used)
binding.pry
TbCommerce::Coupon.update(:used => used + 1)
binding.pry
update(used: @coupon.used + 1)
binding.pry
@coupon.increment!(:used)
binding.pry
Coupon.update(:used => used + 1)
binding.pry

increment_coupon_used!на самом деле следующее:

def increment_coupon_used!
 coupon.increment_used! if coupon.present?
return true

def increment_used!
 update(:used => used + 1)
end

Последнее (?) обновление: Похоже, что у регистратора есть ошибка, которую я получаю.NoMethodError: неопределенный метод `increment! 'на @ coupon.increment! (: используется) и даже на TbCommerce :: Coupon.increment! (: используется)

1 Ответ

0 голосов
/ 17 мая 2018

Итак, пара вопросов присутствовала. Во-первых, это были отношения, и я их не правильно понял. Я закончил тем, что сделал:

cart.increment_coupon_used!

В корзину фактически включена модель ValidatesCoupon, которая имеет отношение для заказа.

Другая проблема, которая присутствует, заключается в том, что локальное приложение переопределяет этот драгоценный камень. Так что это никогда не будет работать, пока я не включу модель тележки.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...