I'm working with Stats of players and I got this data.
Stat model = id: integer, pts: float, user_id: integer, created_at: datetime, updated_at: datetime
So there is a chance that user_id has 2 or more data.
{id: 1, pts: 2, user_id: 1, created_at: datetime, updated_at: datetime}
{id: 2, pts: 8, user_id: 1, created_at: datetime, updated_at: datetime}
{id: 3, pts: 10, user_id: 2, created_at: datetime, updated_at: datetime}
I need to get the average pts per user_id then order it by pts. To get the top scorer.
EDIT
I've fixed this using:
stat = Stat.group(:user_id).sum("pts")
new_value = Hash[*stat.sort_by { |k,v| -v }[0..9].flatten] # To get top 1 to 10
Thank you!
You can do it with a simple query:
hash = Stat.group("user_id").average('pts')
Its will return a hash containing user_id as key and their average points scored as value.
Now to order you can order this hash as:
Hash[h.sort_by{|k, v| v.to_i}.reverse]
This will return a hash sorted in descending order by points.That means the first element in the hash would be the top scorer.
Note: v.to_i is use to handle nil cases.
Try this...
Stat.group(:user_id).order('average_pts DESC').average(:pts)
Other option.
In controller:
#users = User.joins(:stats).select("users.*, stats.user_id, stats.pts, AVG(stats.pts) avg_pts").group('stats.user_id').order("avg_pts DESC")
In view, to be formatted as you like:
<% #users.each do |user| %>
<p><%= user.name %> | <%= user.avg_pts %></p>
<% end %>
Related
The object string log appearing in some pages, how can I remove this?:
"Tv id: 1, name: "SUPER HD", juridica: false, created_at: "2017-06-12 15:55:24", updated_at: "2017-06-12 15:55:24", points: 10>, #<Tv id: 2, name: "ULTRA HD", juridica: true, created_at: "2017-06-12 15:55:35", updated_at: "2017-06-12 15:55:40", points: 15"
Check the image:
Remove the = from your iterator, maybe you have something like:
<%= #variable.each do |value| %>
So, that's printing the each block, try changing it to:
<% #variable.each do |value| %>
In order to just print the content that's being iterated.
<%=#variable%>
It Used to display values
So u dont use
=
in your conditions
you use "=" below
<%=form_for%>
I'm building a most viewed post feature for a simple blog. Each post has a view count that is increased when the Show action is called for that particular post. Then on the Dashboard , I'm trying to list the top 5 posts. So far my code works and returns an array of posts with the post with the highest number of view count being the first index and the last index in the array being the post with the lowest view count. The only thing is when I try to iterate through the array in the view , the view returns:
ERROR
undefined method `title' for nil:NilClass
WHY??? Does it have to do with the "#" infront of the object?
Heres my code.
Dashboard View
<h3> Post </h3>
<% #top_posts.each do |post| %>
<%= post.title %>
<% end %>
Controller Methods
def get_top
#top_posts = []
counts = []
#posts = Post.all
#posts.each do |post|
counts << post.view_count
end
#posts.each do |post|
if counts.max(5).include?(post.view_count)
counts.max(5).each do |n|
if n == post.view_count
#top_posts[counts.max(5).index(n)] = post
end
end
end
end
end
def dashboard
#posts = Post.all
get_top
end
The Top Podcast Array of objects
[#<Post id: 6, title: "Post 6", desc: "", tags: "", view_count: 8, s_desc: "", c_photo: nil, photos: nil, created_at: "2017-06-14 06:02:25", updated_at: "2017-06-15 01:38:40", featured: nil>, #<Post id: 3, title: "post 3", desc: "", tags: "", view_count: 5, s_desc: "", c_photo: nil, photos: nil, created_at: "2017-06-14 05:35:32", updated_at: "2017-06-14 05:35:53", featured: nil>, #<Post id: 5, title: "Post 5", desc: "", tags: "", view_count: 4, s_desc: "", c_photo: nil, photos: nil, created_at: "2017-06-14 06:02:20", updated_at: "2017-06-15 01:38:31", featured: nil>, nil, #<Post id: 4, title: "Post 4", desc: "", tags: "", view_count: 3, s_desc: "", c_photo: nil, photos: nil, created_at: "2017-06-14 05:49:29", updated_at: "2017-06-15 01:38:50", featured: nil>]
The other answer would probably solve your error, but just want to make an attempt to optimize your code.
That array, loop, etc. is unnecessary, ask your db to do that stuff and get the top posts. Fetching all posts and looping over it multiple times...nay, try the following, hopefully this is what you are looking for..
#top_posts = Post.order('view_count desc').limit(5)
That's it, your view needs no change and will work as expected.
Try:
#top_posts << post
instead of:
#top_posts[counts.max(5).index(n)] = post
You don't need to set the array index.
I have an employee model and a sales model, an employee has_many sales. I want to pull the weekly sales for each employee,
so far I can get a collection of all the sales for the current week for each employee;
def weekly_sales
self.sales.where(created_at: (Date.today.beginning_of_week..(Date.today.beginning_of_week + 5)))
end
which gives;
<ActiveRecord::AssociationRelation [#<Sale id: 1054, amount: 2668, new_sale: true, created_at: "2015-07-21 00:00:00", updated_at: "2015-07-21 11:48:03", employee_id: 17>, #<Sale id: 1053, amount: 7128, new_sale: false, created_at: "2015-07-21 00:00:00", updated_at: "2015-07-21 11:48:03", employee_id: 17>, #<Sale id: 1052, amount: 4781, new_sale: true, created_at: "2015-07-20 00:00:00", updated_at: "2015-07-21 11:48:03", employee_id: 17>, #<Sale id: 1051, amount: 4491, new_sale: true, created_at: "2015-07-20 00:00:00", updated_at: "2015-07-21 11:48:03", employee_id: 17>]>
I want to end up with an array that has 5 elements, each is the sale.amount total for each day monday to friday but I'm not sure how to correctly build it.
Runninng weekly sales on a tuesday would give a 5 element array e.g [ 350,290,0,0,0]
This will give you a hash, with dates as keys, and values, which are the sum of sales for this date (and it only makes one query to the db):
def weekly_sales
sales.group("DATE(created_at)").count
end
To get the sum of all sales, grouped by date:
def weekly_sales
sales.group("DATE(created_at)").sum(:amount)
end
i hope this one will give you your desired output
def weekly_sales
self.sales.where(created_at: (Date.today.beginning_of_week..(Date.today.beginning_of_week + 5))).group("DATE(sales.created_at)").sum("sales.amount")
end
I have a Friend model:
user_id, friend_id, status (approved, pending, ignored)
I want to query if user1 & user 2 have a record.
user1.id = 10
user2.id = 9
The Friend Model could have either
10,9,x
9,10,x
How can I write a rails query that will see if a record exists, for either combination? Thanks
How about:
Friend.where(:user_id => [user.id, self.id], :friend_id => [user.id, self.id], :status => 'x')
Converted to SQL would be:
"SELECT \"friends\".* FROM \"friends\" WHERE \"friends\".\"user_id\" IN (10, 9) AND \"friends\".\"friend_id\" IN (10, 9) AND \"friends\".\"status\" = 'x'"
It would return both cases with the one query:
[#<Friend id: 1, user_id: 10, friend_id: 9, status: 'x', created_at: "2011-06-25 15:09:00", updated_at: "2011-11-01 18:28:50">, #<Friend id: 2, user_id: 9, friend_id: 10, status: 'x', created_at: "2011-06-25 15:11:06", updated_at: "2011-11-01 18:28:50">]
I am trying to populate a ruby on rails select box from a database query, the data comes from 3 tables.
My query
#data = Session.all :include => { :term => :courses }
Object
!ruby/object:Session
attributes:
created_at: 2010-06-17 22:12:05
term_id: "15"
updated_at: 2010-06-17 22:12:05
id: "3"
course_id: "1"
attributes_cache: {}
term: &id003 !ruby/object:Term
attributes:
number: "1"
start_date: 2010-06-17
created_at: 2010-06-17 22:12:05
updated_at: 2010-06-17 22:12:05
id: "15"
attributes_cache: {}
courses:
- &id001 !ruby/object:Course
attributes:
created_at:
updated_at:
course_name: Beginner
id: "1"
date:
course_type: Programming
attributes_cache: {}
what i am trying to do is to have the term number followed by the data data and then the course
like this
1 01-09-10 Programming Beginners
The id for the option would be the session_id
any ideas ?
Thanks
Alex
in your erb template you can put the following code withing you form:
<%= select("session","id", #data.map{|d| ["#{d.term.number} #{d.term.start_date} #{d.course.course_type} #{d.course.course_name}",d.id]} %>