[英]How can i refactor this Ruby, Rails code?
我是Rails的新手...是否有更好的方法來重構此代碼:
def get_product_price_minimum
Product.minimum(:price).to_i
end
def get_product_price_maximum
Product.maximum(:price).to_i
end
您可以定義類似“ prices”(一種模糊的方法名稱,以避免使用get_或set_前綴)之類的東西來期望一個參數,該參數將是查詢模型的最大值或最小值:
def prices(what)
Product.public_send(what, :price).to_i
end
然后,可以通過將最小值或最大值作為符號或字符串傳遞來使用它。
我不確定您的函數是否有效,但是可以嘗試(如果price是column,而price是int而不是字符串)
def get_product_price_minimum
Product.order('price').last
end
def get_product_price(value) #value max or min as sym or string
Product.pluck(:price).send(value.to_s)
end
或任何你想要的
upd:這是不執行的操作-如果您已將列定價為整數,則已經顯示的代碼很容易-只需刪除.to_i
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.