简体   繁体   English

Rails将属性分配给实例

[英]rails assign attributes to instance

I am trying to calculate how much the total cost of my transaction will be. 我正在尝试计算交易的总费用。 And to test I am running Transaction.last.calculate_total_payment , it is returning a BigDecimal which is what I want but none of the attributes are being updated on the instance after. 为了测试我正在运行Transaction.last.calculate_total_payment ,它返回一个BigDecimal ,这是我想要的,但是此后实例上的任何属性均未更新。 What am I doing wrong? 我究竟做错了什么?

class Transaction < ActiveRecord::Base
    has_one :auction
    has_one :bid
    belongs_to :inventory_part      
    TIER0 = 0
    TIER1 = 5_000
    TIER2 = 50_000
    TIER3 = 500_000
    TIER4 = 1_000_000
.
.
.
.

    def calculate_total_payment
    part = self.bid.part_price

    self.tax = part * self.tax_rate

    if self.bid.tx.shipping_account
        self.final_shipping_cost = 0 
    else # testing purposes
        self.final_shipping_cost = self.bid.est_shipping_cost
    end
    price_before_fees = part + self.tax + self.final_shipping_cost

    if price_before_fees < TIER1 #5,000
      self.bid_aero_fee = price_before_fees * 0.025
      self.armor_fee = price_before_fees * 0.015
    elsif price_before_fees < TIER2 #50,000
      self.bid_aero_fee = (price_before_fees - TIER1) * 0.015 + 125
      self.armor_fee = (price_before_fees - TIER1) * 0.01 + 75
    elsif price_before_fees < TIER3 #500,000
      self.bid_aero_fee = (price_before_fees - TIER2) * 0.0125 + 800
      self.armor_fee = (price_before_fees - TIER2) * 0.0075 + 525
    elsif price_before_fees < TIER4 #1,000,000
      self.bid_aero_fee = (price_before_fees - TIER3) * 0.0075 + 6425
      self.armor_fee = (price_before_fees - TIER3) * 0.005 + 3900
    else # anything over a million
        self.bid_aero_fee = (price_before_fees - TIER4) * 0.0075 + 10175
        self.armor_fee = (price_before_fees - TIER4) * 0.0035 + 6400
    end

    self.total_fee = self.armor_fee + self.bid_aero_fee
    self.total_amount = price_before_fees + self.total_fee
  end
end

You are never calling save in the calculate_total_payment method. 您永远不会在calculate_total_payment方法中调用save You need to explicitly save the object for it to be persisted in the DB. 您需要显式保存对象以使其保留在数据库中。

You should call save! 您应该致电save! at the end if you want to make your changes persistent in the database. 最后,如果要使更改持久化在数据库中。 Without this, it will modify the object in place (so changes will disappear after reloading of fetching the object again). 如果不这样做,它将在适当的位置修改对象(因此更改将在重新加载以再次获取对象之后消失)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM