簡體   English   中英

將購物車的“總價”屬性連接到付款配置

[英]Connecting a shopping cart “total price” attribute to a payments configuration

我開始將包含產品,購物車和付款的應用程序放在一起。 首先,通過轉到/ products將產品添加到購物車中。 然后,如果您導航到/ cart,系統將填充您准​​備結帳的產品列表。 該計划是將購物車表中的“總價”屬性鏈接到付款表中。

如何鏈接來自單獨表的兩個屬性以使它們相同? 我已經標記了兩個必須相同的屬性,即“總價”和“金額”。

create_payments.rb

class CreatePayments < ActiveRecord::Migration
def change
  create_table :payments do |t|
    t.string :first_name
    t.string :last_name
    t.string :last4
    ***t.decimal :amount, precision: 12, scale: 3***
    t.boolean :success
    t.string :authorization_code

    t.timestamps null: false
    end
  end
end

create_order_items.rb

class CreateOrderItems < ActiveRecord::Migration
def change
  create_table :order_items do |t|
    t.references :product, index: true, foreign_key: true
    t.references :order, index: true, foreign_key: true
    t.decimal :unit_price, precision: 12, scale: 3
    t.integer :quantity
    ***t.decimal :total_price, precision: 12, scale: 3***

    t.timestamps null: false
    end
  end
end

請讓我知道是否需要其他文件來幫助解決問題。 預先感謝您提供任何類型的幫助!

我認為您在這里尋找的是編寫自定義“ getter”方法,即虛擬屬性。 您還可以覆蓋save或使用(活動記錄回調)[ http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html]

例如:

class Payment < ActiveRecord::Base
  has_many :order_items

  # --------
  # option 1
  # --------

  def amount
    # sums up the total price of the associated order items
    self.order_items.pluck(:price).sum
  end

  # --------
  # option 2
  # --------

  def save(*args)
    self.amount = self.order_items.pluck(:price).sum
    super(*args)
  end

  # ----------
  # option 3
  # ----------

  before_save :set_amount
  def set_amount
    self.amount = self.order_items.pluck(:price).sum
  end

end

使用第一個選項(“自定義獲取器”),聚合列不會存儲在數據庫中,並且每次訪問其值時都會動態重新計算。

使用第二個選項(“覆蓋保存”),只要在記錄上調用saveamount列就會自動設置。

我認為第三個選擇可能是最好的。 它與選項2基本上具有相同的作用,但看起來更干凈。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM