Hey guys,
I’m sure this is very simple but i just can’t figure it out.
I have profiles and each time a user visits a profile, the visit is
recorded in the following model…
profile_views
id
user_id #the id of the user who is visiting the profile
profile_user_id #the id of the user who is being visited
viewed_at
This is what I am trying to do (in sudo code)
Find all the visitors for a particular profile only returning each
visitor once and order the whole list by viewed_at
This would be an example list…
Mike, 1 min ago
Scott, 2 mins ago
Andy, 3 mins ago
etc etc
This is what I have do far…
@latest_visitors = ProfileView.find(:all, :conditions =>
[“profile_user_id = ?”, params[:id]], :order => ‘viewed_at DESC’, :limit
=> 5, :group => ‘user_id’)
This returns something along the line of what I want - it returns only 1
record for each user, but it returns the very first time that user
visited the profile.
Any ideas what I’m doing wrong?
Thank you!!
Try this:
@latest_visitors = ProfileView.find(:all,
:conditions => [“profile_user_id = ?”, params[:id]],
:select => ‘id, user_id, profile_user_id, max(viewed_at) viewed_at’,
:limit => 5, :group => ‘user_id’)
You’ll have to include any other fields you need in the “select” option.
Snowman wrote:
Try this:
@latest_visitors = ProfileView.find(:all,
:conditions => [“profile_user_id = ?”, params[:id]],
:select => ‘id, user_id, profile_user_id, max(viewed_at) viewed_at’,
:limit => 5, :group => ‘user_id’)
You’ll have to include any other fields you need in the “select” option.
That worked a treat! thank you!!
I added an ‘:order’ clause to it and it does everything i want.
Was it ok to add the ‘:order’ or is this bad form?
@latest_visitors = ProfileView.find(:all,
:conditions => [“profile_user_id = ?”, params[:id]],
:select => ‘id, user_id, profile_user_id, max(viewed_at)
viewed_at’,
:limit => 5, :group => ‘user_id’, :order => “viewed_at DESC”)
oops. Meant to add your updated code
Was it ok to add the ‘:order’ or is this bad form?
Can’t see any reason not to, if it does what you need. I should have
left it in but I didn’t pay close enough attention to the description of
what you were trying to achieve.