Reputation: 573
My Rails app has a user model and a pins model. pins are album reviews that get posted to the site and the pins belong_to the user. I have a stats page on the site that lists interesting stats about the site's content. I'm trying to list a "Reviewer of the week" which will show which user posted the most reviews over the last week. This is the code I put in my page controller:
@user_week = User.includes(:pins).where('created_at >= ?', 1.week.ago.utc).count(:all, :group => 'name', :order => 'count(*) DESC').first
I then call it in the view:
<%= @user_week[0] %>
For some reason this is giving me a user, but not actually the user with the most posts over teh last week. It gives me ["User", 1] and it doesn't change when I post more often. Is my code wrong?
Also, how can I call the user's image from @user_week? It currently returns the name and pin count.
User column names:
["id", "email", "encrypted_password", "reset_password_token", "reset_password_sent_at", "remember_created_at", "sign_in_count", "current_sign_in_at", "last_sign_in_at", "current_sign_in_ip", "last_sign_in_ip", "created_at", "updated_at", "name", "image_file_name", "image_content_type", "image_file_size", "image_updated_at", "slug", "twitter", "lastfm", "status", "admin"]
Pin column names:
["id", "description", "created_at", "updated_at", "user_id", "image_file_name", "image_content_type", "image_file_size", "image_updated_at", "image_remote_url", "artist", "album", "date", "rank", "video_html", "video", "rating", "year"]
Upvotes: 0
Views: 843
Reputation: 1062
@users = User.joins(:pins).group('users.id').where('pins.created_at >= ?', 1.week.ago.utc).order('count(pins.id) desc').limit(1).first
will return an array of users. then use the following code
<%= link_to (image_tag @user.image(:small)), @user %>
Upvotes: 1
Reputation: 573
I was able to get the user.image to display by using this in the view:
<% @users.each do |user| %>
<% if @user_week[0] == user.name %>
<%= link_to (image_tag user.image(:small)), user %>
<% end %>
<% end %>
Upvotes: 0