Mongoid sort Model based on array size which is in other Model (has_one) relation

会有一股神秘感。 提交于 2019-12-12 03:09:53

问题


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



来源:https://stackoverflow.com/questions/38372455/mongoid-sort-model-based-on-array-size-which-is-in-other-model-has-one-relatio

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!