1

我有三个模型用户、活动和活动记录。

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :token_authenticatable, :confirmable,
  # :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  # Setup accessible (or protected) attributes for your model
  attr_accessible :first_name, :last_name, :email, :gender, :password, :password_confirmation, :remember_me
  # attr_accessible :title, :body

  has_many :activities 
  has_many :activity_records , :through=> :activities
end

class Activity < ActiveRecord::Base
  attr_accessible :point, :title
  belongs_to :user
  has_many :activity_records
end

class ActivityRecord < ActiveRecord::Base
    attr_accessible :activity_id
    belongs_to :activity

    scope :today, lambda { where("DATE(#{'activity_records'}.created_at) = '#{Date.today.to_s(:db)}'")}
end

我想查询用户的所有活动以及他们今天各自活动记录的计数。例如,查询并转换为 json 格式后,我想有类似下面的内容

[
   { 
      id: 23
      title: "jogging",
      point: "5",
      today_activity_records_count: 1,
   },
   { 
      id: 12
      title: "diet dinner",
      point: "2",
      today_activity_records_count: 0,
   },
]

请指导我如何实现这一目标。

谢谢

4

2 回答 2

1

我不完全确定这是你想要的,但我希望我能让你走上正轨:

User.joins(:activity_record)
    .group(:activity_id) 
    .select("'user'.id, title, point, count('activity_records'.id) as today_activity_records_count")

然后尝试.to_json该结果。

一个测试它的好方法(所以你可以看到SQL结果)是在rails 控制台

编辑:

再次阅读您的问题,我认为您正在寻找特定用户的活动,因此:

Activity
    .joins(:activity_records, :user)
    .select("'activities'.id, title, point, COUNT('activity_records'.id) AS today_activity_records_count")
    .group("activities.id")
    .where(user_id: your_desired_user_id_here)
于 2013-06-29T03:18:32.360 回答
0

请试试这个:

@activities = Activity.select("activities.id,activities.title,activities.point, COUNT(activity_records.id) AS today_activity_records_count").joins(:activity_records, :user).where("DATE(activity_records.created_at) = (?)", Time.now).group("activities.id")

当你想输出 json

@activities.to_json
于 2013-06-29T03:46:45.483 回答