简体   繁体   中英

Ruby on Rails Active Record Query Interface

I have the following:

models/like.rb :

class Like
    belongs_to :post
end

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.

You can use counter_cache to do this. 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):

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM