Rails 3 many-to-many query on includes or joins
Posted
by
Myat
on Stack Overflow
See other posts from Stack Overflow
or by Myat
Published on 2013-06-29T02:49:03Z
Indexed on
2013/06/29
4:21 UTC
Read the original article
Hit count: 101
ruby-on-rails
|activerecord
I have three models User, Activity and 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
I would like to query all activities for a user together with the count for their respective activity records for today. For example, after querying and converting to json format, I would like to have something like below
[
{
id: 23
title: "jogging",
point: "5",
today_activity_records_count: 1,
},
{
id: 12
title: "diet dinner",
point: "2",
today_activity_records_count: 0,
},
]
Please kindly guide me how I can achieve that.
Thanks
© Stack Overflow or respective owner