我的目标是按总票数对帖子进行排序。正如您在控制器中看到的,首先我按创建的__排序帖子,这有效!但是我想改变它,所以它将按总票数排序。投票来自acts_as_votable gem。哪个与Post
相关联目前这是我的帖子控制器:
def index
# @posts = Post.all.order("created_at DESC") <--This works
@posts = Post.includes(:votes).order("votes_for.size desc")
end
当我运行此操作时,我收到以下错误:在Post上找不到名为'votes'的关联;也许你拼错了?
我的猜测是包括在这里不起作用。
当我打开rails控制台时。为了测试关联,我得到以下结果:
@post = Post.first
@post.votes_for.size
这表明我目前有2票。
最后这是我的Post.rb模型
class Post < ActiveRecord::Base
acts_as_votable
belongs_to :user
has_many :comments
has_attached_file :image, styles: { medium: "700x500>#", small: "350x250>" }
validates_attachment_content_type :image, content_type: /\Aimage\/.*\Z/
end
提前致谢!!! (我正在使用psql)
添加架构:
create_table "posts", force: :cascade do |t|
t.string "title"
t.string "link"
t.text "description"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "user_id"
t.string "image_file_name"
t.string "image_content_type"
t.integer "image_file_size"
t.datetime "image_updated_at"
end
create_table "users", force: :cascade do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", default: 0, null: false
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.string "current_sign_in_ip"
t.string "last_sign_in_ip"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "name"
end
add_index "users", ["email"], name: "index_users_on_email", unique: true, using: :btree
add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true, using: :btree
create_table "votes", force: :cascade do |t|
t.integer "votable_id"
t.string "votable_type"
t.integer "voter_id"
t.string "voter_type"
t.boolean "vote_flag"
t.string "vote_scope"
t.integer "vote_weight"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "votes", ["votable_id", "votable_type", "vote_scope"], name: "index_votes_on_votable_id_and_votable_type_and_vote_scope", using: :btree
add_index "votes", ["voter_id", "voter_type", "vote_scope"], name: "index_votes_on_voter_id_and_voter_type_and_vote_scope", using: :btree
add_foreign_key "comments", "posts"
add_foreign_key "comments", "users"
end