Omar Omar -4 years ago 104
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 but for some reason when I want it to be for [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:


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


class UsersController < ApplicationController
before_action :authenticate_user!

def index
@users = User.all

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


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
resources :posts do
resource :like, module: :posts
root to: "posts#index"


<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} %>
<% end %>

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download