Rails 3对包含或连接的多对多查询

时间:2013-06-29 02:49:03

标签: ruby-on-rails activerecord

我有三个模型User,Activity和ActivityRecord。

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,
   },
]

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

谢谢

2 个答案:

答案 0 :(得分: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 console

修改

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

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)

答案 1 :(得分: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