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
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})")`
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)