簡體   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