Mongoid sort Model based on array size which is in

2019-09-19 04:51发布

问题:

I have Postactivity model, which has post_id as the foreign key of the Post Model (has_one relation) and this Postactivity model has the likes array.

How i can sort Post model by likes?

class Post
  has_one :postactivity, foreign_key: :post_activity_id, class_name:"PostActivity"
end

class PostActivity
  field :likes, type: Array  
  belongs_to :post, foreign_key: :post_id, class_name: "Post"
end

回答1:

class PostActivity
  field :likes, type: Array
  field :likes_count, type: Integer, default: 0 
  belongs_to :post, foreign_key: :post_id, class_name: "Post"

  before_save do
    self.likes_count = lies.size
  end
end

Now you can sort PostActivity model by likes_count field.

PostActivity.order_by(:likes_count => :desc)

You will have sorted PostActivity instances. If you will need post, you can get them by call:

PostActivity.order_by(:likes_count => :desc).first.post


回答2:

posts =Array.new
PostActivity.order_by(:likes_count => :desc).each do |pa|
posts << pa.post
end
this worked for me