繁体   English   中英

在Rails中定义模型方法

[英]Defining model methods in Rails

目前,我有一个Order,OrderItems和Products模型。 我想在OrderItems中定义一个称为小计的方法,该方法将返回数量乘以价格的值(通过关系product.price)。

我该怎么做? 我不知道如何通过关系访问列和列。

class OrderItem < ActiveRecord::Base
belongs_to :order
belongs_to :product

validates :order_id, presence: true
validates :product_id, presence: true

def subtotal
    quantity * product.price
end
end

表架构

create_table "order_items", force: :cascade do |t|
t.integer  "product_id"
t.integer  "order_id"
t.integer  "quantity"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end

谢谢你的帮助。

有点不确定OrderItems和Products之间的关系,但是如果您完成了belongs_to: products models/OrderItems.rb ,那么您可以简单地进行quantity * product.price

我认为在您的订单模型中,您的关系如下:

has_many :order_items

因此,如果您从数据库中获取订单行,则为了计算总数,可以使用以下代码。

在OrderItem类中定义一个称为total_price的方法。

def total_price

  tot_price = self.product.price * self.quantity

  tot_price
end

那么你可以这样称呼它

order = Order.first
total_price = order.order_items.sum(&:total_price)

暂无
暂无

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

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