【发布时间】: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