首页 > 解决方案 > 如何根据用户兴趣自定义排序?

问题描述

在现有的产品控制器中,我们根据价格对产品进行分类。

def index
  @products = Product.all.order(price: :asc)
  @products = @products.paginate(:page => params[:page], :per_page => 20)
end

现在,我想更改排序,以便我们将用户兴趣。总体排序策略如下:

  1. 属于用户感兴趣类别的项目将列在顶部。其余项目将在之后列出。

  2. 在用户感兴趣的分组内,按价格订购产品。(不感兴趣的分组的类似方法)。

用户表

id  name    interested_categories   
1   Alice   [ 10, 11 ]  
2   Bruce   [ 11 ]  
3   Carol   [ 10, 12 ]  

类别表

id  category_name       
10  School      
11  Kitchen     
12  Camping

产品表

id  product_name price category_id
1   pencil       2     10

标签: ruby-on-railsactiverecord

解决方案


你可以试试这个

def index
  filtered_products = Product.where(category_id: current_user.interested_categories)
  all_products = Product.where.not(category_id: current_user.interested_categories).order(price: :asc)
  @final_products = (filtered_products+all_products).paginate(:page => params[:page], :per_page => 20)
end

然后您的视图采用@final_products或只是将变量更改为@products


推荐阅读