Rails sort users by method - ruby-on-rails

I'm trying to rank my user's in order of an integer. The integer I'm getting is in my User Model.
def rating_number
Impression.where("impressionable_id = ?", self).count
end
This gives each User on the site a number (in integer form). Now, on the homepage, I want to show an ordered list that places these user's in order with the user with the highest number first and lowest number second. How can I accomplish this in the controller???
#users = User....???
Any help would be appreciated!
UPDATE
Using this in the controller
#users = User.all.map(&:rating_number)
and this for the view
<% #users.each do |user| %>
<li><%= user %></li>
<% end %>
shows the user's count. Unfortunately, the variable user is acting as the integer not the user, so attaching user.name doesn't work. Also, the list isn't in order based on the integer..

The advice here is still all kinds of wrong; all other answers will perform terribly. Trying to do this via a nested select count(*) is almost as bad an idea as using User.all and sorting in memory.
The correct way to do this if you want it to work on a reasonably large data set is to use counter caches and stop trying to order by the count of a related record.
Add a rating_number column to the users table, and make sure it has an index defined on it
Add a counter cache to your belongs_to:
class Impression < ActiveRecord::Base
belongs_to :user, counter_cache: :rating_number
end
Now creating/deleting impressions will modify the associated user's rating_number.
Order your results by rating_number, dead simple:
User.order(:rating_number)

The advice here is just all kinds of wrong. First of model your associations correctly. Secondly you dont ever want to do User.all and then sort it in-memory based on anything. How do you think it will perform with lots of records?
What you want to do is query your user rows and sort them based on a subquery that counts impressions for that user.
User.order("(SELECT COUNT(impressions.id) FROM impressions WHERE impressionable_id = users.id) DESC")
While this is not terribly efficient, it is still much more efficient than operating with data sets in memory. The next step is to cache the impressions count on the user itself (a la counter cache), and then use that for sorting.
It just pains me that doing User.all is the first suggestion...

If impressions is a column in your users table, you can do
User.order('impressions desc')
Edit
Since it's not a column in your users table, you can do this:
User.all.each(&:rating_number).sort {|x,y| y <=> x }
Edit
Sorry, you want this:
User.all.sort { |x, y| y.rating_number <=> x.rating_number }

Related

Check if value in one table is present in another

So this is probably easy but I haven't been able to find the right method for it. I have 2 models. One called monitor, and one called follower.
In 'monitor' I have a column called owner_id.
In 'follower' I have a column called follower_id.
What I would like to do is check if any of these match up (I'd like to get a count, not a boolean output). Both belongs_to Users.
How do I go about doing this?
Situation
I am trying to calculate a conversion rate from Twitter. Where the follower and the follower ids are the users who is following your account.
On the monitor I let you monitor keyword and interactions, where I save the owner_id (the person you're communicating with).
Now I count all the conversations you have had. Then I want to see how many of those that have turned into following your company.
I have a model called campaigns where you can monitor certain keywords.
<% #campaigns.each do |campaign| %>
<%= campaign.keyword %>
<% end %>
The model looks like this:
class Campaign < ActiveRecord::Base
has_many :alerts
end
now what I want to do is track the conversion rate for that specific campaign.
( CODE HERE* / campaign.alerts.count ) * 100
where CODE HERE* should be the count of how many that exists between :
campaign.alerts.map(&:owner_id)
and
current_user.followers.map(&:follower_id)
so what you are trying to do is just to compare two big arrays of ids (campagin.alerts.map(&:owner_id) and current_user.followers.map(&:follower_id)) and count how many ids are the same, you can use count and count everything that your block expression evaluates as true, and save that on a variable that you will use on your division, something like this:
result = (campagin.alerts.map(&:owner_id).count do |id|
current_user.followers.map(&:follower_id)).include?(id)
end
( result / campaign.alerts.count ) * 100
There are many other ways like using Array#all or other methods, maybe you can look at them here and see what fits you most:
http://ruby-doc.org/core-2.2.0/Array.html#method-i-2D

Rails best way to get previous and next active record object

I need to get the previous and next active record objects with Rails. I did it, but don't know if it's the right way to do that.
What I've got:
Controller:
#product = Product.friendly.find(params[:id])
order_list = Product.select(:id).all.map(&:id)
current_position = order_list.index(#product.id)
#previous_product = #collection.products.find(order_list[current_position - 1]) if order_list[current_position - 1]
#next_product = #collection.products.find(order_list[current_position + 1]) if order_list[current_position + 1]
#previous_product ||= Product.last
#next_product ||= Product.first
product_model.rb
default_scope -> {order(:product_sub_group_id => :asc, :id => :asc)}
So, the problem here is that I need to go to my database and get all this ids to know who is the previous and the next.
Tried to use the gem order_query, but it did not work for me and I noted that it goes to the database and fetch all the records in that order, so, that's why I did the same but getting only the ids.
All the solutions that I found was with simple order querys. Order by id or something like a priority field.
Write these methods in your Product model:
class Product
def next
self.class.where("id > ?", id).first
end
def previous
self.class.where("id < ?", id).last
end
end
Now you can do in your controller:
#product = Product.friendly.find(params[:id])
#previous_product = #product.next
#next_product = #product.previous
Please try it, but its not tested.
Thanks
I think it would be faster to do it with only two SQL requests, that only select two rows (and not the entire table). Considering that your default order is sorted by id (otherwise, force the sorting by id) :
#previous_product = Product.where('id < ?', params[:id]).last
#next_product = Product.where('id > ?', params[:id]).first
If the product is the last, then #next_product will be nil, and if it is the first, then, #previous_product will be nil.
There's no easy out-of-the-box solution.
A little dirty, but working way is carefully sorting out what conditions are there for finding next and previous items. With id it's quite easy, since all ids are different, and Rails Guy's answer describes just that: in next for a known id pick a first entry with a larger id (if results are ordered by id, as per defaults). More than that - his answer hints to place next and previous into the model class. Do so.
If there are multiple order criteria, things get complicated. Say, we have a set of rows sorted by group parameter first (which can possibly have equal values on different rows) and then by id (which id different everywhere, guaranteed). Results are ordered by group and then by id (both ascending), so we can possibly encounter two situations of getting the next element, it's the first from the list that has elements, that (so many that):
have the same group and a larger id
have a larger group
Same with previous element: you need the last one from the list
have the same group and a smaller id
have a smaller group
Those fetch all next and previous entries respectively. If you need only one, use Rails' first and last (as suggested by Rails Guy) or limit(1) (and be wary of the asc/desc ordering).
This is what order_query does. Please try the latest version, I can help if it doesn't work for you:
class Product < ActiveRecord::Base
order_query :my_order,
[:product_sub_group_id, :asc],
[:id, :asc]
default_scope -> { my_order }
end
#product.my_order(#collection.products).next
#collection.products.my_order_at(#product).next
This runs one query loading only the next record. Read more on Github.

How can I sort on a calculated value?

I'm currently building an NFL pick'em league site. I have a Users model, a Games model, and join table which captures each user's individual picks. The games model has a "result" attribute which either consists of "W" for win, "L" for loss, "P" for push (tie).
I am running into issues building a standings page. I currently have two methods in my Users model:
def correct_games
self.games.where(result: "W").count
end
def total_games
self.games.where('result != ?', "P").count
end
The correct_games method counts the user's picks that were correct. The total_games methods counts the number of total games (not counting games that resulted in a push).
Then in my view I currently have for each user: <%= number_to_percentage(current_user.correct_games.to_f / current_user.total_games) %>
This division gives me that user's win percentage (# correct/total picks). For my standings table, I obivously want a descending order on win percentage. The issue is the only solutions to sorting seem to be using the .order method which usually requires some attribute to already be in the database which you can then call in the controller.
I've also tried adding this win percentage attribute to the database, but I can't seem to figure out a callback that will update the User's score whenever the game results are updated.
Any solutions to either sorthing on an attribute that is calculated in the view or a way to add this win percentage to the users model?
Thanks in advance!
Why not just do the calculation in the model instead of in the view? Add another method like this:
This code goes in your User model:
def percentage_correct
((self.correct_games.to_f / self.total_games) * 100).to_i
end
def self.sorted_by_percentage_correct
User.all.sort_by(&:percentage_correct).reverse
end
This is how you use it in your view:
<% User.sorted_by_percentage_correct.each do |u| %>
<div><%= u.name %> has pick percentage of <%= u.percentage_correct %>%</div>
<% end %>

Selective ActiveRecord

Say I'm having a table 'Users'.
A user can exist 3 times (records) in my table, in 3 different states (state1, state2, state3).
First state1 will be created, then state2, ...
If state3 exists, I don't want to look at state1 and state2 anymore, but I'll have to keep them in my table, for later purposes.
All 3 records have the same uuid.
If I want to collect all users, I can't use User.all (because he will give me all 3 states for the same user).
Is there a short solution for this in my model? Now I'm collecting all uuid's and for each uuid I'll check which is the latest state, then I put those records in an array.
Problem with this array is that it is just 'an array', instead of an ActiveRecord object.
#uuid = []
#users = [] #will contain only the latest states at the end
User.all.each do |u|
#uuid << u.uuid unless #uuid.includes?(u.uuid)
end
#uuid.each do |u|
if user = User.find_by_state_and_uuid(3, u)
#users << user
elsif user = User.find_by_state_and_uuid(2, u)
#users << user
elsif user = User.find_by_state_and_uuid(1, u)
#users << user
end
end
Any ideas how I can translate this logic to an ActiveRecord object?
In short: User.magic_function to return only the latest state of each uuid
Thanks in advance!
Wouter
If you plan ahead, you can always sort on your state and return the "highest" one. This works well if you have a linear progression from one to the next. As an example:
user = User.where(:uuid => u).order('users.state DESC').first
For more complicated transitions you're not going to be able to use this trick. You could try using a different column for ordering, such as fetching the last by created_at time.
From a design perspective it seems highly unusual to have several user records in different states. A better plan might be to split out the state-driven part of the user record into a separate table and do the state tracking there, everything linked back to a singular user record.
Have you looked into using scopes? You should be able to create a scope for each User state, and then use those for querying.
Try :
User.get_user(state, uuid)
And make the scope in your user model :
scope :get_user, lambda { |*args| { :conditions => ["state = ? AND uuid = ?",args.first , args.second ] }}

How to Average Multiple Columns in Rails

I have the following objects: Products, Ratings, and Users. I am trying to filter and select a number of Products that the User owns (through a has_many :through relationship with UserProducts) and average a certain column the Ratings table that matches their User ID and the correct Product ID.
So, my function is something along these lines:
def find_rating(criteria)
product = self.products.find(:all, :conditions => ["criteria = ?", criteria])
rating = self.ratings.where("product_id = ?", product).average(:overall)
end
I think that I'm going about this the wrong way, because I'm trying to find a product_id by passing an entire array of data consisting of multiple products. But, I think of using a more traditional loop and that seems convoluted. Can someone point me in the right direction for solving this problem? Thanks!
If product is a single entry, as it appears to be in your code, I would do this:
rating = self.products.find_by_criteria(criteria).ratings.average(:overall)
If it's an array of products, this method may help you: http://apidock.com/rails/ActiveRecord/Batches/ClassMethods/find_each

Resources