在Rails中定义模型方法

时间:2016-07-10 01:11:05

标签: ruby-on-rails rails-activerecord

目前我有Order,OrderItems和Products模型。我想在OrderItems中定义一个名为subtotal的方法,它将返回数量的值乘以价格(通过关系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

感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

对OrderItems和产品之间的关系有点不确定,但如果您在belongs_to: products中完成了models/OrderItems.rb,那么您只需执行quantity * product.price

答案 1 :(得分:0)

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

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)