我的应用程序中有一个基本的blog
/comments
情况,我正在尝试在应用程序中创建一个"评论最多的博客"部分。
我的comment.rb
型号有这个:
class Comment < ApplicationRecord
belongs_to :user, optional: true
belongs_to :blog, optional: true, counter_cache: true
end
在我的blogs_controller.rb
:中
@commented_blogs = Blog.where("published_on <= ?", Date.today).order('comments_count DESC').limit(3)
然而,当我尝试在视图中迭代@commented_blogs
时,我会得到以下错误:
SQLite3::SQLException: no such column: comments_count: SELECT "blogs".* FROM "blogs" WHERE (published_on <= '2018-12-06') ORDER BY comments_count DESC LIMIT ?
我觉得我需要在数据库中添加一列,但我查看的文档中没有提到任何迁移。有人能帮忙吗?
附加信息
以下是我的blogs
和comments
:模式
create_table "blogs", force: :cascade do |t|
t.string "title"
t.string "teaser"
t.text "body"
t.string "category", default: "General"
t.string "linked_module"
t.boolean "published", default: false
t.datetime "published_on"
t.integer "user_id"
t.integer "image_id"
t.integer "pdf_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "slug"
t.string "cta_read_more", default: "Read More"
t.string "cta_pdf", default: "Get My Free PDF"
t.string "cta_video", default: "Watch the Video"
t.string "convertkit_data_form_toggle"
t.string "convertkit_href"
t.integer "pin_image_id"
t.string "data_pin_description"
t.string "freebie_filename"
t.string "video_link"
t.string "freebie_type", default: "File"
t.string "freebie_description"
t.index ["image_id"], name: "index_blogs_on_image_id"
t.index ["pdf_id"], name: "index_blogs_on_pdf_id"
t.index ["pin_image_id"], name: "index_blogs_on_pin_image_id"
t.index ["slug"], name: "index_blogs_on_slug", unique: true
t.index ["user_id"], name: "index_blogs_on_user_id"
end
create_table "comments", force: :cascade do |t|
t.text "body"
t.integer "user_id"
t.integer "blog_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.boolean "approved", default: false
t.boolean "read", default: false
t.string "email"
t.string "name"
t.index ["blog_id"], name: "index_comments_on_blog_id"
t.index ["user_id"], name: "index_comments_on_user_id"
end
如果您想使用counter_cache
,您确实需要在博客表中添加一个comments_count
列(如文档中所示(:
尽管在包含belongs_to声明,则必须添加实际列关联的(has_many(模型。在上述情况下,您需要将名为books_count的列添加到Author模型中。
如果你不想存储comments_count
(即去掉counter_cache
(,你可以使用另一个答案提到的解决方案,它可以动态计算comments_count
:
@commented_blogs = Blog.left_outer_joins(:comments).select('blogs.*, count(comments.*) as comments_count').group(:id).order(comments_count: :desc).limit(3)