我正在开发一个简单的 Rails 应用程序,它允许用户为项目添加书签并将其添加到集合中。我想按照集合中的项目添加到集合中的日期对集合中的项目进行排序。
商品型号:
class Item < ApplicationRecord
belongs_to :user
belongs_to :category
has_many :collection_items
has_many :collections, through: :collection_items
end
集合模型:
class Collection < ApplicationRecord
belongs_to :user
has_many :collection_items
has_many :items, through: :collection_items
end
Collection_Item 模型:
class CollectionItem < ApplicationRecord
belongs_to :item
belongs_to :collection
end
如果尝试通过created_at订购商品(参见下面的代码):
def show
@collection_items = @collection.items.order(created_at: :desc)
end
但这当然会按照项目首次创建的日期对它们进行排序,而不是按照项目添加到集合中的日期。 我怎样才能实现后者?
非常感谢您的帮助:)
最佳答案
添加到集合中的日期应该是CollectionItem
的created_at
。因此,您可以做的就是通过以下方式订购商品:
@collection.items.includes(:collection_items).order('collection_items.created_at DESC')
关于ruby-on-rails - 按添加日期对集合中的项目进行排序 (Rails),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48284261/