Arif Arif - 3 months ago 7
Ruby Question

Arrange items in an array by the time they were added to that array?

Basically I have a Collection model and a Post model, where a Collection has many posts and a Post belongs to many collections. So I'll occasionally push posts to the

@collection.posts
array using
<<
, to replicate a post being added to a collection. Now is there a way to order the posts in
@collection.posts
by the time they were pushed to that array? If yes, how?

All relevant models:

user.rb

class User < ActiveRecord::Base

has_many :posts, dependent: :destroy
has_many :collections, dependent: :destroy
end


post.rb

class Post < ActiveRecord::Base

belongs_to :user
has_many :collectables
has_many :collections, through: :collectables
end


collection.rb

class Collection < ActiveRecord::Base
belongs_to :user
has_many :collectables
has_many :posts, through: :collectables
end


collectable.rb

class Collectable < ActiveRecord::Base
belongs_to :post
belongs_to :collection
end

Answer

I guess adding an order scope to the definition of the association would work:

# in collection.rb
has_many :posts,
         -> { order('collectables.created_at DESC') },
         through: :collectables