我有以下课程,
class Event < ActiveRecord::Base
has_many :user_calendars, :dependent => :destroy
belongs_to :user
end
class User < ActiveRecord::Base
has_many :events
has_many :user_calendars
end
class UserCalendar < ActiveRecord::Base
belongs_to :event
belongs_to :user
end
我希望能够找到属于最多usercalendars的前n个事件
我创建了以下函数来获取将用户添加到用户日历的用户数。
@count = UserCalendar.where('event_id = ?', event_id).count
我仍然不确定添加顶部的最佳方式是什么。
答案 0 :(得分:1)
此查询将提供event_id
n次
select *,count(*) as count from user_calendar group by event_id having count(*) = n order by count desc
在Rails中实现
# Replace n with yours
event_ids = UserEvent.find_by_sql("select *,count(*) as count from user_calendar group by event_id having count(*) = n order by count desc").map(&:id) rescue []
Event.where("id in (?)",event_ids)
注意:根据我的理解,您希望UserEvent
中的event_ids不会发生。如果我错了就发表评论。