【问题标题】:Rails order active records with assign_attributesRails 使用 assign_attributes 订购活动记录
【发布时间】: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


【解决方案1】:

当您在关系上调用.each 时,它会返回一个数组,因此您可以使用Array#sort_by

@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

@fiche_order_algo.sort_by!{|f| f.scoring.score}

如果您正在处理大型数据集,这可能不会被优化,但不会比您已有的效率低。

但您也可以一次性完成:

@fiche_order_algo.sort_by! do |f|
  if f.geo.id != @geo.id
    f.user.scoring.assign_attributes(score: (f.user.scoring.score - 10.0))
  end
  f.user.scoring.score
end

【讨论】:

  • 我刚试过,我觉得还是一样,更新的顺序没有变化
  • 我错过了sort_by! 上的爆炸声,它修改了它被调用的数组。试试看吧。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-02
  • 1970-01-01
  • 1970-01-01
  • 2012-04-18
  • 2013-02-01
相关资源
最近更新 更多