我怎样才能重构这个Ruby,Rails代码



我是Rails的新手...有没有更好的方法来重构这段代码:

  def get_product_price_minimum
    Product.minimum(:price).to_i
  end
  def get_product_price_maximum
    Product.maximum(:price).to_i
  end

您可以定义类似 "price"(一个模糊的方法名称,以避免使用 get_ 或 set_ 前缀(之类的东西来期望一个参数,这将是查询模型的最大值或最小值:

def prices(what)
  Product.public_send(what, :price).to_i
end

然后,您可以通过将最小值或最大值作为符号或字符串传递来使用它。

我不确定你的函数是否有效但你可以试试(如果价格是列,价格是整数而不是字符串(

def get_product_price_minimum
      Product.order('price').last
end

最新更新