【问题标题】:Sort a list of Items in Rails based on Likes done by Users根据用户的点赞数对 Rails 中的项目列表进行排序
【发布时间】:2016-12-10 22:15:03
【问题描述】:

我是 ruby​​ on rails 的新手,所以请原谅这个问题。我尝试按照此示例Rails sort tags by most used (tag.posts.count) 进行操作,但一直收到错误消息“未定义的方法 `order' for Items:Module”。我正在尝试根据项目的喜好对项目列表进行排序。所以一个有 5 个赞的项目应该放在一个只有 3 个赞的项目之上。我在下面列出了所有相关代码。非常感谢你们!!

点赞.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 %>

迁移相关

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

结束 结束

【问题讨论】:

    标签: ruby-on-rails database views


    【解决方案1】:

    在 users_controller.rb 中

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

    【讨论】:

    • Zaur 感谢您的回答。虽然这让屏幕出现,但没有实现“喜欢”的排序。它仍然显示按创建时间排序。一些有 5 个赞的项目低于之前创建的没有赞的项目。
    • 我还添加了我的迁移,以便您查看它们是如何创建的。非常感谢您的帮助,先生
    • 您在数据库中看到正确的点赞数了吗?您可能需要使用以下代码重置计数器: Item.each { |item| Item.reset_counters(item.id, :likes) }
    • 我要把它放在我的 index.html.erb 中吗?再次感谢 Zaur
    • 另外你只需要在关联的belongs_to一侧指定:counter_cache选项。
    猜你喜欢
    • 1970-01-01
    • 2019-02-16
    • 2012-09-29
    • 1970-01-01
    • 1970-01-01
    • 2021-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多