[英]Ruby on Rails Active Record Query Interface
I have the following: 我有以下几点:
models/like.rb
: models/like.rb
:
class Like
belongs_to :post
end
models/post.rb
: models/post.rb
:
class Post
has_many :likes, dependent: :destroy
def self.popular
Like.group(:post_id).count << ???
end
end
I would like to make a scope that returns the most popular posts: posts with more than 20 likes, but I don't know how to make the conditional. 我想设置一个范围,使其返回最受欢迎的帖子:具有20个以上点赞的帖子,但我不知道如何设置条件帖子。
You can use counter_cache to do this. 您可以使用counter_cache来执行此操作。 You will have to create an extra column, but it is more performatic when SELECTing.
您将不得不创建一个额外的列,但是在进行选择时,它的性能更高。
models/like.rb
class Like < ActiveRecord::Base
belongs_to :post, counter_cache: true
end
models/post.rb
class Post < ActiveRecord::Base
has_many :likes, dependent: :destroy
def self.popular
where('likes_count > 20').order('likes_count DESC')
end
end
Then create the migration: 然后创建迁移:
class AddLikesToPosts < ActiveRecord::Migration
def change
add_column :posts, :likes_count, :integer, default: 0
end
end
And populate likes_count
for your current Posts on rails console
(only needed if you already have some created posts): 并在
rails console
上为当前的Posts填充likes_count
(仅当您已经有一些创建的post时才需要):
Post.find_each { |post| Post.reset_counters(post.id, :likes) }
After this, each time you create a new Like, the counter will be automatically incremented. 此后,每次创建新的“赞”时,计数器都会自动递增。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.