ruby-on-rails - 如何根据用户兴趣自定义排序?
问题描述
在现有的产品控制器中,我们根据价格对产品进行分类。
def index
@products = Product.all.order(price: :asc)
@products = @products.paginate(:page => params[:page], :per_page => 20)
end
现在,我想更改排序,以便我们将用户兴趣。总体排序策略如下:
属于用户感兴趣类别的项目将列在顶部。其余项目将在之后列出。
在用户感兴趣的分组内,按价格订购产品。(不感兴趣的分组的类似方法)。
用户表
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
解决方案
你可以试试这个
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
推荐阅读
- javascript - 如何使用相同的输入按钮附加多个图像
- excel - 合适的 Excel VBA 循环函数?
- java - 打印文件内容的问题
- linux - 我的 crontab 连续运行不到 1 分钟
- git-commit - 重新提交的内容是否与原始提交的内容不同?
- c - mingw 环境中 64 位字符串格式化程序的警告
- javascript - 为什么 getAttribute('href') 与 reduce 一起使用时会返回完整的 URL?
- linux - 如何更好地诊断哪个客户端导致高 Xorg CPU 使用率?
- android - 其他人可以访问我的 sqlite 数据吗?
- ios - Firebase 和 Swift