【问题标题】:Connecting a shopping cart "total price" attribute to a payments configuration将购物车“总价”属性连接到付款配置
【发布时间】:2016-08-09 16:40:45
【问题描述】:

我开始构建一个应用程序,其中包括产品、购物车和付款。您首先通过转到 /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

如果需要任何其他文件来帮助解决问题,请告诉我。提前感谢您提供任何类型的帮助!

【问题讨论】:

  • 相同是什么意思?
  • 我基本上想用 order_items 表中的“total_price”属性替换 payment 表中的“amount”属性。因此,当用户付款时,它会根据购买的产品填充欠款。
  • 我认为您需要在您的payments 中添加一个belongs_to 对您的Order 的引用,并在您的付款中添加一个has_one。这样您就可以简单地获取所有OrderItems 的价格并填充amount 属性之类的。 payment.amount = payment.order.order_items.select("total_price").reduce(&amp;:+)

标签: ruby-on-rails ruby payment-gateway shopping-cart product


【解决方案1】:

我认为您在这里寻找的是编写自定义“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

使用第一个选项(“自定义 getter”),聚合列不会存储在数据库中,而是在每次访问它的值时动态重新计算。

使用第二个选项(“覆盖保存”),只要在记录上调用 save,就会自动设置 amount 列。

在我看来,第三个选项可能是最好的。它基本上与选项 2 做同样的事情,但看起来更干净一些。

【讨论】:

    猜你喜欢
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    • 2013-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-11
    • 2013-01-30
    相关资源
    最近更新 更多