I'm using the where
method to lookup and compare two columns in two separate tables for identical values (order & player - both integers). I'm trying to count the number of times the lookup is successful (meaning successfully matches columns) for the current user, and then put that into an instance variable (<%= @total %>) to be displayed on the current user's index view (Once I have the count I'm multiplying by 5, but that's arbitrary). The real-world application for this could be a leaderboard-type-thing as users make different predictions and can be ranked based on how well those predictions match results.
Searched several answers that seemed to be in the neighborhood (Counting occurrences of a given input) but not quite getting me toward a solution (counting occurrences of items in an array python). (How to count the number of times two values appear in two columns in any order)
Predictions Controller:
def index
if current_user.present?
@predictions = current_user.predictions.order(:order)
else
@predicitons = Prediction.all
end
@total = Result.where({ :order => @current_user.predictions.pluck(:order), :player_id => @current_user.predictions.pluck(:player_id) }).uniq.count*5.to_i
end
def new
if current_user.predictions.count < '32'.to_i
@prediction = Prediction.new(player_id: params[:player_id])
else
redirect_to "/predictions", alert: "You've maxed out on predictions"
end
end
def create
@prediction = current_user.predictions.build(predictions_params)
if @prediction.save
redirect_to "/predictions/new", notice: "This prediction's just been created."
else
redirect_to "/predictions", alert: "Something happened."
end
end
def edit
end
Results Controller:
def new
@result = Result.new
end
def create
@result = Result.new(results_params)
if @result.save
redirect_to "/results"
else
render "New"
end
end
Tried different code in the predictions controller, index action. What I have here comes closest but I'm not getting consistent results as it counts every prediction, right and wrong. I've tried setting the variable to '0'.to_i before the lookup, but still getting inconsistent results.
@total = '0'.to_i
I feel like I'm overlooking something fairly obvious to more experienced eyes. I realize also there are more advanced ways to accomplish this that I'm not aware of. A suggestion was made to store the variable in a session or cookie which is outside of my experience but I'm continuing to research this as an option.
Thanks for any feedback.
Example db entry match:
=> #<Prediction id: 126, round: nil, number: nil, created_at: "2017-03-21 05:44:32", updated_at: "2017-03-21 13:05:11", player_id: 2, order: 2, user_id: 2 >
=> #<Result id: 98, info: nil, created_at: "2017-04-20 15:37:17", updated_at: "2017-04-20 15:37:17", player_id: 2, order: 2>