【问题标题】:Rails DISTINCT query doesn't work when doing iterationRails DISTINCT 查询在进行迭代时不起作用
【发布时间】:2018-07-20 23:06:58
【问题描述】:

我想为用户显示上次访问的位置。作为考虑,用户可能会多次访问该位置,所以我只想在最后一次 location_id 出现在运行活动中时显示该位置。 我使用带有此代码的 Rails 查询

runnings = @current_user.
  runnings.
  where(with_friend: true).
  order('created_at DESC').
  distinct('location_id').
  select([:location_id, :created_at])

完美运行。它不会两次显示相同的跑步活动

#<Running id: nil, created_at: "2018-02-09 12:51:48", location_id: 10>

我也可以得到基于location_id的位置

locations = Location.where('id in (:location_ids)', location_ids: runnings.map {|running| running.location_id})

顺便说一句,我有 21 个虚拟跑步数据,而位置仅显示 10 个,这正是我的预期。 但是当我尝试使用此代码从运行中获取 created_at 属性时

runnings.map {|running| running.created_at.to_i}

它再次显示 21 条数据,除非我将其更改为数组或 json,它也显示 21 条数据,否则我无法计算它。 我的代码有什么问题?你能帮我解决吗?非常感谢。

【问题讨论】:

  • 你能显示从你的查询中生成的 SQL 吗?
  • locationids.length 给你 21?我怀疑 with_friend: true 正在过滤记录

标签: mysql ruby-on-rails ruby sqlite


【解决方案1】:

Distinct 适用于所有选定的列,而不仅仅是 location_id,如您所料。您可以使用group 来解决您的问题:

runnings = @current_user.
  runnings.
  where(with_friend: true).
  select('MAX(created_at), location_id').
  group(:location_id, :created_at)

【讨论】:

  • 选择通话后忘记.
  • 它有效,但 created_at 似乎不想用 .distinct(:location_id) 区分自己
  • 您的查询中有多少 runnings 返回?生成的查询是否只有一个 location_id
猜你喜欢
  • 1970-01-01
  • 2018-11-08
  • 1970-01-01
  • 1970-01-01
  • 2017-03-13
  • 1970-01-01
  • 2014-09-18
  • 1970-01-01
  • 2017-08-03
相关资源
最近更新 更多