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