Omar Omar - 1 month ago 10
Ruby Question

Setting up a Like Counter on Rails from scratch

Was trying to set up a ranking score for my users depending on their like counts.

I was able to get this to work for current_user.like.count but for some reason when I want it to be for user.like.count [so that its not the same one for everyone] my app crashes and gives me this error message: "Undefined method `likes' for nil:NilClass" I have put all my relevant code below as well as my github for this. Any help would be amazing.

Github Url: https://github.com/OmarZV/TY2

_rankings.html.erb

<% if current_user.likes.count >3 %>
A Ranking
<% elsif %>
<% current_user.likes.count == 2%>
B Ranking
<% else %>
C Ranking
<% end %>


users_controller.rb

class UsersController < ApplicationController
before_action :authenticate_user!

def index
@users = User.all
end

def show
@users = User.find(params[:id])
end
end


routes.rb

Rails.application.routes.draw do
devise_for :users, :controllers => { :omniauth_callbacks => "users/omniauth_callbacks" }
resources :users, :controllers => "users_controller.rb"
resources :users do
resource :ranking, module: :users
end
resources :posts do
resource :like, module: :posts
end
root to: "posts#index"
end


Index.html.erb

<h1 class="page-header">Platform Users</h1>
<% @users.each do |user| %>
<strong><%= user.username %></strong>
<div class="round-image-50"><%= image_tag(user.avatar.url(:thumb)) %></div>
div id="user_<%= @user_id%>_rankings">
<%= render partial: "rankings", locals: {user: @user} %>
</div>
<% end %>

Answer

Moving comment to answer.

Id just loop through and not use a partial probably. But im pretty sure you can just pass locals: {user: user} to use the variable from the loop and not the instance variable from your controller. checkout the docs on it for a bit more details http://guides.rubyonrails.org/layouts_and_rendering.html#using-partials