我想列出产品的售价。产品has_many
product_varients
[原文]和product_varients
属于product
。 Product
表有一个名为selling_price
的列。 Product_varients
表还有一个字段selling_price
。如果销售价格在product_varients
表中,则应该使用此selling_price
,否则应从selling_price
表中获取product
。
这是我的代码:
class Product
has_many :product_varients, dependent: :destroy
def selling_price_by_body_type vehicle
self.product_varients.select {|pv| pv.body_type == vehicle.body_type}.first.try(:selling_price) || self.selling_price
end
end
这就是我调用方法的方法:
product.selling_price_by_body_type(@vehicle)
这对我不起作用。我想将其修改为使用三元条件或if
... else
。请帮帮我。
答案 0 :(得分:2)
我会这样做:
class Product
has_many :product_varients, dependent: :destroy
def selling_price_by_body_type(vehicle)
self.product_varients.where(body_type: vehicle.body_type).first&.selling_price || self.selling_price
end
end
注意:
where
代替select { ... }.first
来减少返回的记录数。&.
是另一种在rails 5中编写.try()
的方式。答案 1 :(得分:1)
以下是同一个ternary operator
:
class Product
has_many :product_varients, dependent: :destroy
def selling_price_by_body_type vehicle
self.product_varients ? self.product_varients.select {|pv| pv.body_type == vehicle.body_type}.first.try(:selling_price) : self.selling_price
end
end