julianx
julianx

Reputation: 35

Order items of a collection by date added (Rails)

I'm working a simple Rails app that lets users bookmark Items and add them to Collections. I would like order the items within a collection by the date they were added to that collection.

Item Model:

class Item < ApplicationRecord
  belongs_to :user
  belongs_to :category
  has_many :collection_items
  has_many :collections, through: :collection_items
end

Collection Model:

class Collection < ApplicationRecord
  belongs_to :user
  has_many :collection_items
  has_many :items, through: :collection_items 
end

Collection_Item Model:

class CollectionItem < ApplicationRecord
  belongs_to :item
  belongs_to :collection
end

If tried ordering the items by created_at (see code below):

def show
  @collection_items = @collection.items.order(created_at: :desc)
end

But this will of course order them by the date the item was first created - not by the date the item has been added to the collection. How could I achieve the latter?

Many thanks for your help :)

Upvotes: 2

Views: 191

Answers (1)

IngoAlbers
IngoAlbers

Reputation: 5802

The date of the addition to the collection should be the created_at of the CollectionItem. So what you could do is to just order the items by this:

@collection.items.includes(:collection_items).order('collection_items.created_at DESC')

Upvotes: 2

Related Questions