如何获得min has_many rec ords的记录(加入数据)

Has*_*mad 8 ruby activerecord join ruby-on-rails

user.rb

has_many :properties
Run Code Online (Sandbox Code Playgroud)

property.rb

belongs_to :user
Run Code Online (Sandbox Code Playgroud)

我希望得到一个拥有最小属性的用户,例如明智的max.

我无法找到任何与此相关的查询

M. *_*rim 7

要查找user具有min属性的信息,您可以

User.joins(:properties).group("properties.user_id").order("count(properties.user_id) desc").last
Run Code Online (Sandbox Code Playgroud)

并找到user具有max属性,

User.joins(:properties).group("properties.user_id").order("count(properties.user_id) desc").first
Run Code Online (Sandbox Code Playgroud)

注:由于其联接与操作properties,所以user没有properties在此查询将不会出现.


ret*_*oat 5

你可以用counter_cache.

:counter_cache选项可用于更有效地查找所属对象的数量.

这里开始

belongs_to :user, counter_cache: true
Run Code Online (Sandbox Code Playgroud)

然后创建迁移:

def self.up
  add_column :users, :properties_count, :integer, :default => 0

  User.reset_column_information
  User.find(:all).each do |u|
    User.update_counters u.id, :properties_count => u.properties.length
  end
end
Run Code Online (Sandbox Code Playgroud)

然后你可以获取有最大值的用户 properties_count

User.maximum("properties_count")
Run Code Online (Sandbox Code Playgroud)

这是一个关于counter_cache 的令人敬畏的RailsCast