1

我能够使用硬编码金额成功结帐,即:

def checkout
    nonce = params["payment_method_nonce"]

    if current_user.braintree_id?
        customer = Braintree::Customer.find(current_user.braintree_id)
    else
        @result = Braintree::Customer.create(
            email: current_user.email,
            payment_method_nonce: params[:payment_method_nonce]
          )
          customer = result.customer
          current_user.update(braintree_id: customer.id)
end

     @result = Braintree::Transaction.sale(
      amount: **"10.00"**,
      payment_method_nonce: nonce
    )

    if @result.success? 
        redirect_to root_path, notice: "You have successfully checked out"
    else
        flash[:alert] = "Something went wrong while processing your transaction"
        render :new
    end
end

假设我希望 current_user 能够以存储在我的 rails 数据库中的特定“价格”购买我的投资组合的访问权限。有没有办法通过从数据库中的对象属性中提取金额来设置金额,即:“<=@portofolio_item.price>”?我已经尝试了多次,但没有任何运气。我可能做错了什么?

4

1 回答 1

1

正如 Rails 框架的文档中所述:

ActiveRecord 基础知识

您需要从 PortfolioItems 模型表中映射一个新字段。为此,您首先需要通过创建迁移将该字段添加到表中,我建议使用小数,因为如果您在逗号后限制数量,浮点数可能会导致问题。

每个portfolio_item 的价格都应该以十进制形式存储,比例为2:

t.decimal :price, scale: 2, precision: 5

这将允许该项目具有与之关联的价格,并使方法:@portfolio_item.price可用。

然后你只需要在你的控制器中替换:

 @result = Braintree::Transaction.sale(
      amount: **"10.00"**,
      payment_method_nonce: nonce
    )

和:

 @result = Braintree::Transaction.sale(
      amount: @portfolio_item.price,
      payment_method_nonce: nonce
    )
于 2017-11-27T18:02:25.107 回答