Balaji Thiru
Balaji Thiru

Reputation: 15

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

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

Upvotes: 0

Views: 102

Answers (2)

Balaji Thiru
Balaji Thiru

Reputation: 15

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

Upvotes: 1

Farkhat Mikhalko
Farkhat Mikhalko

Reputation: 3645

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

Upvotes: 1

Related Questions