2016-05-26 13 views

Trả lời

7

Để tìm số user với min thuộc tính bạn có thể si mply làm,

User.joins(:properties).group("properties.user_id").order("count(properties.user_id) desc").last 

Và để tìm ra user với max tài sản,

User.joins(:properties).group("properties.user_id").order("count(properties.user_id) desc").first 

Lưu ý: Bởi vì một mình tham gia hoạt động với properties, vì vậy user không có properties sẽ không xuất hiện trong truy vấn này.

5

Bạn có thể sử dụng counter_cache.

Tùy chọn :counter_cache có thể được sử dụng để giúp tìm số lượng đối tượng thuộc sở hữu hiệu quả hơn.

Từ here

belongs_to :user, counter_cache: true 

Sau đó tạo sự di cư:

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 

Sau đó, bạn có thể lấy sử dụng mà có max properties_count

User.maximum("properties_count") 

Dưới đây là một tuyệt vời RailsCast về counter_cache

4

Tôi nghĩ bạn có thể làm như thế này bởi phạm vi

class User 
    has_many :properties 
    scope :max_properties, 
    select("users.id, count(properties.id) AS properties_count"). 
    joins(:properties). 
    group("properties.id"). 
    order("properties_count DESC"). 
    limit(1) 

    scope :min_properties, 
    select("users.id, count(properties.id) AS properties_count"). 
    joins(:properties). 
    group("properties.id"). 
    order("properties_count ASC"). 
    limit(1) 

Và chỉ cần gọi User.max_properties và User.min_properties

CẬP NHẬT:

Nó sẽ aslo công việc như BoraMa suggeted

class User 
    has_many :properties 
    scope :max_properties, 
    select("users.*, count(properties.id) AS properties_count"). 
    joins(:properties). 
    group("users.id"). 
    order("properties_count DESC"). 
    limit(1) 

    scope :min_properties, 
    select("users.*, count(properties.id) AS properties_count"). 
    joins(:properties). 
    group("users.id"). 
    order("properties_count ASC"). 
    limit(1) 
+0

Tôi nghĩ rằng bạn nên nhóm bởi 'users.id' và không' properties.id' cho điều này để làm việc. Ngoài ra, bạn có thể chọn 'users. *' Thay vì chỉ 'id' để người dùng trả về có thể sử dụng như một bản ghi đường ray bình thường với tất cả các thuộc tính. – BoraMa

+1

@BoraMa, @Thorin bạn có thể nhóm theo 'users.id' và chỉ chọn' users.id' thay vì 'users. *' Vì 'users. *' Chỉ hỗ trợ trong 'mysql'. 'PG' không cho phép chọn các cột khác với cột nhóm và hàm tổng hợp –

Các vấn đề liên quan