active_record返回所有匹配记录对象

时间:2016-02-05 03:22:24

标签: ruby-on-rails activerecord psql

我正在尝试查找一种方法来查询我的数据库,以便为所有匹配的记录返回一个关联的记录。 e.g:

如果用户有很多房屋,(房屋属于用户),我需要获得所有用户,每个用户都有一个相关的房子(比如第一个房子)。我该怎么做?

详细说明:

user A has houses 1, 2, 3
user B has houses 4, 5, 6
user C has houses 7, 8, 9
  • 为了获得所有用户,我可以这样做:user.all
  • 为了获得用户的所有房屋,我可以这样做:<user>.houses
  • 为了吸引用户的住所,我可以加入查询:User.joins(:houses).where(<condition>)

但是,如果我希望以下列格式获取所有用户和每个房子:

user   |   house
-----------------
A      |   1
B      |   4
C      |   7

我该如何解决这个问题?

数据库是postgres。

更新

我的真实模型如下:

class Product < ActiveRecord::Base

  ...

  has_many :product_pictures, :dependent => :destroy
  accepts_nested_attributes_for :product_pictures, allow_destroy: true
end

2 个答案:

答案 0 :(得分:1)

为用户添加关系:

class User < ActiveRecord::Base
  # Your current code
  has_one :house, -> { where('houses.id IN (SELECT min(id) FROM houses GROUP BY user_id)')}
end

然后,您的查询将是:

users = User.joins(:house)

- 更新 如果您想过滤结果,请自由添加where子句

users = User.joins(:house).where(your_filter_conditions)

答案 1 :(得分:0)

result = User.joins(:houses).select("users.*, SOMEFUNCTION(houses.id) AS house_id").group(:id)

# you can access single house id like
result.first.house_id

您可以选择SOMEFUNCTION您要选择哪个门牌号。

如果你使用postgresql,

User.joins(:houses).select("users.*, (array_agg(houses.id))[1] AS house_id").group(:id)
相关问题