user
has_many devices
。ActiveRecord:如何从连接查询中选择单个列?
编辑:device
有registration_id
场
我想获得用户,然后某个用户设备的所有registration_id
的数组。
我想:
@user.followers.join(:devices).select("devices.registration_id")
但似乎工作, 我怎么能做到这一点查询?
user
has_many devices
。ActiveRecord:如何从连接查询中选择单个列?
编辑:device
有registration_id
场
我想获得用户,然后某个用户设备的所有registration_id
的数组。
我想:
@user.followers.join(:devices).select("devices.registration_id")
但似乎工作, 我怎么能做到这一点查询?
我不知道,但认为这应该工作:
@user.followers.map { |f| f.devices.pluck(:registration_id) }.flatten
UPD:为了尽量减少查询数,我可以提供这个解决方案:
Device.where(user_id: @user.followers.pluck(:id)).pluck(:registration_id)
它返回所需的结果,但它查询每个用户ID的设备表,因此对于n个用户有n个查询。有没有更有效的方法来做到这一点? –
我已经添加了另一个解决方案 – ck3g
try by swapping
@user.select("devices.registration_id").followers.join(:devices)
NoMethodError:私人方法'选择'要求#<用户:0x00000004fa3440> –
您可能要重新检查设备和注册之间的关联
Device
belongs_to :user
has_one :registration #but in this case the device_id should be in Registration
考虑registration_id是设备
arr = @user.followers.collect(&:id)
@user.devices.collect{|d| d.registration_id if arr.include?d.follower_id}
@user.followers.join(:devices).select("devices.registration_id")
的领域,如果你。加入后把多余的连接S的关系的工作。它被称为.joins(“devices”)
'Device.find_all_by_user_id(@ user.follower_ids)''?你会得到整个设备模型,但这很重要吗? –