SQL - Order records by the closest value

后端 未结 2 1113
谎友^
谎友^ 2020-12-22 09:36

I have created one API for product details In this API I also need to attach similar products in response.

So for similar products scenario are like following 1) Pri

相关标签:
2条回答
  • 2020-12-22 10:01

    Yes you can perform this operation by using just simple order query as like following

    `Product.where("product.category_id = ?", "category_id").order("abs(products.price - #{your_selected_product_price})")`
    
    0 讨论(0)
  • 2020-12-22 10:28

    The previous answer is dangerous to use if the price comes from untrusted user input, since it allows SQL injection. It also breaks if price can be nil.

    The solution is to properly quote the price for the given column:

    class Product < ActiveRecord::Base
      scope :closest_by_price, ->(price) {
        quoted_price = connection.quote(price, columns_hash["price"])
        order("abs(products.price - #{quoted_price})")
      }
    end
    
    Product.closest_by_price(50.0)
    
    0 讨论(0)
提交回复
热议问题