我是铁杆上的红宝石,所以请原谅这个问题。我尝试按照这个例子Rails sort tags by most used (tag.posts.count)但是仍然收到一个错误“项目:模块的未定义方法`顺序”。我正在尝试根据项目的喜好对项目列表进行排序。所以一个有5个喜欢的项目应放在一个只有3个喜欢的项目上方。我在下面列出了我的所有相关代码。非常感谢你们!
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 %>
迁移相关
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
端 端
答案 0 :(得分:1)
在users_controller.rb
中def index
@items = Item.order('likes_count')
end