我有这样一个需求: 三张表:users,checkins,bookmarks 关系:
class User < ActiveRecord::Base has_many :checkins has_many :bookmarks end
class Checkin < ActiveRecord::Base belongs_to :user end
class Bookmark < ActiveRecord::Base belongs_to :user end
在 rails3 中我该如何写能生成以下 sql:
select u.id, u.first_name, u.last_name, (select count() from bookmarks where user_id=u.id) as bookmarks, (select count() from checkins where user_id=u.id) as checkins from users u order by bookmarks desc
就是统计用户的 checkins 和 bookmarks 数量