Omar
Omar

Reputation: 383

Sort a list of Items in Rails based on Likes done by Users

I'm new to ruby on rails so please forgive the question. I tried following this example Rails sort tags by most used (tag.posts.count) but kept getting an error "undefined method `order' for Items:Module". I am trying to sort a list of items based on an item's likes. So an item with 5 likes should be placed above an item with only 3 likes. I have listed below all my relevant code down below. Thank you so much guys!!

Like.rb

class Like < ApplicationRecord
belongs_to :item, :counter_cache => true
belongs_to :user
end

Likes_controller.rb

class Items::LikesController < ApplicationController
before_action :authenticate_user!
before_action :set_book

def create      
    @item.likes.where(user_id: current_user.id).first_or_create             
    respond_to do |format|
        format.html {redirect_to @item}
        format.js
    end
end 
def destroy
    @item.likes.where(user_id: current_user.id).destroy_all

    respond_to do |format|
        format.html {redirect_to @item}
        format.js
    end
end
private 
def set_book
    @item = Item.find(params[:item_id])
end
end

Item.rb

class Item < ApplicationRecord
has_many :likes, :counter_cache => true

users_controller.rb

class UsersController < ApplicationController
before_action :authenticate_user!
before_action :set_user, only: [:show, :edit, :update, :destroy]

def index
@items = Item.all   
Items.order('likes_count')
end

def show
@items = Item.find(params[:id])
end


private

def set_user
    @item = Item.find(params[:id])
end
end

index.html.erb

   <% @items.each do |item| %>
<%=  item.product %>
<div><%= image_tag(item.avatar.url(:thumb)) %></div>
<% end %>

Migrations Relevant

class AddLikecountsToItem < ActiveRecord::Migration[5.0]
def change
add_column :items, :likes_count, :integer, :null => false, :default => 0
 end
end

class CreateLikes < ActiveRecord::Migration[5.0]
def change
create_table :likes do |t|
  t.integer :user_id
  t.integer :item_id

  t.timestamps
end

end end

Upvotes: 1

Views: 374

Answers (1)

Zaur Amikishiyev
Zaur Amikishiyev

Reputation: 378

in users_controller.rb

def index
  @items = Item.order('likes_count')
end

Upvotes: 1

Related Questions