Sql 如何按相关模型的唯一ID计数排序

Sql 如何按相关模型的唯一ID计数排序,sql,ruby-on-rails,Sql,Ruby On Rails,我正在使用Rails 3.1.3、Ruby 1.9.2和MySQL 5.1进行开发。 我想按唯一相关型号的数量订购型号。 这是我的密码 class User < ActiveRecord::Base has_many :check_ins . . end class CheckIn < ActiveRecord::Base belongs_to :user, :counter_cache => true belongs_to :ski_resort,

我正在使用Rails 3.1.3、Ruby 1.9.2和MySQL 5.1进行开发。
我想按唯一相关型号的数量订购型号。 这是我的密码

class User < ActiveRecord::Base
  has_many :check_ins
  .
  .
end

class CheckIn < ActiveRecord::Base
   belongs_to :user, :counter_cache => true
   belongs_to :ski_resort, :counter_cache => true

   .
   .
end

class SkiResort < ActiveRecord::Base
   has_many :check_ins
   .
   .
end
class用户true
属于:滑雪胜地:计数器缓存=>true
.
.
结束
类
我想根据登记入住的滑雪场数量订购用户模型

当用户1在同一滑雪场登记3次时,计数为1。



试试这个:

users = {}
User.all.each do |u|
    users[u] = u.check_ins.uniq.count
end
sorted_users = users.sort_by {|name, check_ins| check_ins}
sorted_users.flatten(1)
(1..sorted_users.count).step(2) do |n|
    sorted_users.delete(n-1)
end
停止编写SQL


注意:可能不起作用:p

因为据我所知,
计数器\u缓存不支持唯一计数,所以存储您自己的计数是最简单的

ski\u resort\u checkin\u count
添加到
用户
中,作为一个整数字段,默认值为0,空值为false

class User < ActiveRecord::Base
  has_many :check_ins
  has_many :ski_resorts, through: :check_ins

  def update_counts!
    update_column :ski_resort_checkin_count, ski_resorts.uniq.count
  end
end

class SkiResort < ActiveRecord::Base
  has_many :check_ins
  has_many :users, through: :check_ins
end

class CheckIn < ActiveRecord::Base
  belongs_to :user
  belongs_to :ski_resort

  after_create  :update_counts!
  after_destroy :update_counts!

  def update_counts!
    user.update_counts!
  end
end
class用户

然后,在添加作用域之前,您可以先执行
User.order(:ski\u resort\u checkin\u count)

检查是否可以编写在Rails控制台中运行的函数。谢谢您的回答。事实上,当入住滑雪场的总人数达到时,您的答案是有效的,但我想添加一些条件来选择特定的季节,例如2011年创建的。对不起,这没有用,您似乎有误解。可能是。我只是个初学者。但是,我仍然认为您不需要原生SQL。
class User < ActiveRecord::Base
  has_many :check_ins
  has_many :ski_resorts, through: :check_ins

  def update_counts!
    update_column :ski_resort_checkin_count, ski_resorts.uniq.count
  end
end

class SkiResort < ActiveRecord::Base
  has_many :check_ins
  has_many :users, through: :check_ins
end

class CheckIn < ActiveRecord::Base
  belongs_to :user
  belongs_to :ski_resort

  after_create  :update_counts!
  after_destroy :update_counts!

  def update_counts!
    user.update_counts!
  end
end