【发布时间】: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