简体   繁体   中英

Defining model methods in Rails

Currently I have an Order, OrderItems and Products model. I want to define a method called subtotal in OrderItems, which will return the value of the quantity times the price (through relationship product.price).

How could I accomplish that? I dont know how to access columns and columns through a relationship.

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

Table schema

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

Thanks for your help.

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

I think in your Order model you have a relationship as follows,

has_many :order_items

Hence, if you fetch an order row from the database then, in order to calculate the total you can use the following code.

Define a method called total_price in OrderItem class.

def total_price

  tot_price = self.product.price * self.quantity

  tot_price
end

then you can call it as follows

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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