如何在Ruby on Rails中以相同的价格对产品进行排序?

时间:2021-10-31 15:59:55

In the show view of my products am using the following function to link to the next product (ordered by price):

在我的产品的展示视图中使用以下功能链接到下一个产品(按价格订购):

class Product < ActiveRecord::Base 

  belongs_to :user

  def next
    Product.where("user_id = ? AND price > ?", user_id, price).order("price ASC").first 
  end

end

This function works as long as all products differ in price. The moment two products have the same price though, the function no longer works because it is always looking for a higher price.

只要所有产品的价格不同,此功能就可以使用。目前两款产品的价格相同,功能不再有效,因为它总是在寻找更高的价格。

How can I make it that a user can click through all his products using the function above, even when some products do not differ in price?

如果用户可以使用上述功能点击所有产品,即使某些产品的价格没有差异,我怎样才能做到这一点?

I tried replacing > with >= but that will always return the same one product, leaving the function essentially useless.

我尝试用> =替换>但是这将始终返回相同的一个产品,使该函数基本无用。

Can anybody help?

有人可以帮忙吗?

2 个解决方案

#1


2  

This method can only work if the products are strictly ordered. A solution could be to sort them by price first and next by id (the condition a bit more complex also):

此方法仅在产品严格订购时才有效。一个解决方案可能是首先按价格对它们进行排序,然后按id进行排序(条件也稍微复杂一些):

def next
  Product.where("user_id = :user_id AND (price > :price OR (price = :price AND id > :id))", user_id: user_id, price: price, id: id)
    .order("price ASC, id ASC").first 
end

If the products have a unique name or label, you could use this attribute instead on the id, so the products with the same price are sorted alphabetically, that could make more sense then the id.

如果产品具有唯一的名称或标签,则可以在id上使用此属性,因此具有相同价格的产品按字母顺序排序,这可能比id更有意义。

#2


1  

Greater than >= plus different product_id

大于> =加上不同的product_id

def next
  Product.
    where("id <> ?", id).
    where("user_id = ?", user_id).
    where("price >= ?", price).
    order("price ASC").
    first 
end

#1


2  

This method can only work if the products are strictly ordered. A solution could be to sort them by price first and next by id (the condition a bit more complex also):

此方法仅在产品严格订购时才有效。一个解决方案可能是首先按价格对它们进行排序,然后按id进行排序(条件也稍微复杂一些):

def next
  Product.where("user_id = :user_id AND (price > :price OR (price = :price AND id > :id))", user_id: user_id, price: price, id: id)
    .order("price ASC, id ASC").first 
end

If the products have a unique name or label, you could use this attribute instead on the id, so the products with the same price are sorted alphabetically, that could make more sense then the id.

如果产品具有唯一的名称或标签,则可以在id上使用此属性,因此具有相同价格的产品按字母顺序排序,这可能比id更有意义。

#2


1  

Greater than >= plus different product_id

大于> =加上不同的product_id

def next
  Product.
    where("id <> ?", id).
    where("user_id = ?", user_id).
    where("price >= ?", price).
    order("price ASC").
    first 
end