如何用select添加三元条件

时间:2018-05-25 06:48:39

标签: ruby-on-rails

我想列出产品的售价。产品has_many product_varients [原文]和product_varients属于productProduct表有一个名为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。请帮帮我。

2 个答案:

答案 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