SkRoR
SkRoR

Reputation: 1199

How to add ternary condition with select

I want to list the selling price of product. Product has_many product_varients [sic], and product_varients belong to product. Product table has a column called selling_price. Product_varients table also has a field selling_price. If selling price is in product_varients table, it should take this selling_price, otherwise it should take selling_price from product table.

This is my code:

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

This is how I am calling the method:

product.selling_price_by_body_type(@vehicle)

This does not work for me. I want to modify it to using a ternary condition or if ... else.

Upvotes: 0

Views: 288

Answers (2)

Jagdeep Singh
Jagdeep Singh

Reputation: 4920

I would do it like this:

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

Note:

  • You can use where in place of select { ... }.first to reduce the number of records returned.
  • &. is another way to write .try() in rails 5.

Upvotes: 2

Sravan
Sravan

Reputation: 18647

Here is the ternary operator for the same:

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

Upvotes: 1

Related Questions