Reputation: 42069
I'm having difficulty getting a scope to work in a Rails app with a pg database. In the show page for groups_controller.rb, I'm trying to display two different types of data ordered by created_at. The first is users who joined the group and second, users who have confirmed attendance for any of the events for the group, and the results could be mixed together like this
user joined group (7 minutes ago)
user confirmed attendance (10 minutes ago)
user joined group (15 minutes ago)
The models are as following
Group.rb
has_many :memberships
has_many :users, through: :memberships
has_many :events
User.rb
has_many :memberships
has_many :groups, through: :memberships
has_many :confirmations
has_many :events, through: :confirmations
Event.rb
has_many :confirmations
has_many :users, through: :confirmations
In the show action of the groups_controller.rb, I created a recent_activities action like this, passing Time.now with the intention of using it to get all the results for the last 24 hours
def show
@recent = Group.recent_activities(Time.now)
end
However, when it came to writing the method in group.rb, I ran into problems. For example, using this format
where( memberships: {created_at: ''}
I didn't know how to calculate within the last 24 hours, or within the last 7 days. I'm sure there's other problems with how I'm trying to do this. Any tips? I've only written a few of these types of queries in my life so they've coming out all mishapen
Group.rb
scope :recent_activities, lambda {|time|
joins(:user, :membership, :confirmation, :event).
where( memberships: {created_at: ''},
confirmations: {created_at: '' })
}
Upvotes: 0
Views: 207
Reputation: 7279
As you are trying to create a feed activity, take a look at this gem, it may help you.
You can see this railscasts too
Upvotes: 0
Reputation: 54902
Try with this:
scope :recent_activities, lambda{ |time|
joins({:memberships => :users}, {:events => :confirmations}).
where('CAST(memberships.created_at as DATE) > :yesterday
AND CAST(confirmations.created_at as DATE) > :yesterday',
yesterday: Date.today - 1.days)
}
(You could add the following relation in your Group model:)
has_many :events
has_many :confirmations, :through => :events
Upvotes: 1
Reputation: 38645
Adding this answer just to show that you can use ago, since methods.
So you could do something like this for "since the last 24 hours" of the time
parameter.
scope :recent_activities, lambda {|time|
joins(:user, :membership, :confirmation, :event).
where("memberships.created_at >= :twenty_four_hours_ago and confirmations.created_at >= :twenty_four_hours_ago", twenty_four_hours_ago: 24.hours.ago(time))
}
Upvotes: 1