ActiveRecord:如何从连接查询中选择单个列?

时间:2012-10-09 10:59:14

标签: ruby-on-rails activerecord

user has_many devices

编辑:device有一个registration_id字段

我希望得到一个用户设备的所有registration_id数组,然后是某个用户。

我正在尝试:

@user.followers.join(:devices).select("devices.registration_id")

但这似乎有效, 我该怎么做这个查询?

4 个答案:

答案 0 :(得分:1)

我不确定但认为这应该有效:

@user.followers.map { |f| f.devices.pluck(:registration_id) }.flatten

更新:为了尽量减少查询次数,我可以提供此解决方案:

Device.where(user_id: @user.followers.pluck(:id)).pluck(:registration_id)

答案 1 :(得分:0)

     try by swapping
        @user.select("devices.registration_id").followers.join(:devices)

答案 2 :(得分:0)

您可能想要重新检查设备和注册之间的关联

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}

答案 3 :(得分:0)

@user.followers.join(:devices).select("devices.registration_id")

如果你在.join之后添加了额外的s,那么应该可行。它被称为.joins(“devices”)

相关问题