【发布时间】:2020-07-01 12:17:11
【问题描述】:
我有一个 User 模型,它的 Scoring 模型具有 score 值。
在我的 Rails 视图中,我想按分数对我的用户进行排序。
=> User.joins (: scoring) .order (: score)
到目前为止,一切都很好。
当我动态更改某些用户的分数而不根据某些属性(例如地理位置)在数据库中修改它们时,它会变得复杂。
我尝试了assign_attributes 函数,但它没有改变,因为.order 函数调用了数据库中的分数字段。
用例:我按地理位置进行用户搜索,地理位置附近的用户连同他们的分数一起出现在我的搜索中。我想加权附近用户的分数,因为他们不在确切的地理位置
我的代码:
#Get scoring in other geolocation
@fiches_proxi = Fiche.joins(:user).merge(User.joins(:scoring)).near([@geo.lat_long_DMS.to_f, @geo.lat_long_grd.to_f], proxi_calcule(@geo.population_2012.to_i),units: :km, :order => 'scorings.score DESC').order('scorings.score DESC').where.not(geo: @geo.id).limit(10)
#Get scoring in real geolocation
@fiche_order_algo_all = Fiche.joins(:user).merge(User.joins(:scoring)).where(geo_id: @geo)
#Find all scores
@fiches_all = Fiche.where(id: @fiche_order_algo_all.pluck(:id) + @fiches_proxi.pluck(:id))
@pagy, @fiche_order_algo = pagy(@fiches_all.joins(:user).merge(User.joins(:scoring).order('scorings.score DESC')), items: 12)
@fiche_order_algo.each do |f|
if f.geo.id != @geo.id
f.user.scoring.assign_attributes(score: (f.user.scoring.score - 10.0))
else
f.user.scoring.score
end
end
我的分数更新了,但我的顺序是一样的!
【问题讨论】:
-
你能贴出你试过的代码吗?
-
苏尔!我更新我的消息
标签: ruby activerecord ruby-on-rails-5