根据关联的创建日期对关联对象进行排序

Sorting associated objects based on the association's creation date

现在,我正在开发一个简单的应用程序。它需要按照我们将它们添加到对象的日期来获取关联对象。为此,我想根据 pivot-table 的 id 对它们进行排序。

我的应用看起来有点像这样:

class Product < ActiveRecord::Base
  has_and_belongs_to_many :users
end

class User < ActiveRecord::Base
  has_and_belongs_to_many :products
end

但是,当用户想要购买产品时,我会在数据透视表中添加一个新关系 table courses_users。当我然后 运行 @product.users 时,我将按照创建用户的顺序取回它们,而不是作为关系添加。

我试过创建查询范围,但没有成功。我还尝试在 has_and_belongs_to_many 上创建订单,例如:

has_and_belongs_to_many :users, order: 'course_users.id ASC'

但是 none 似乎有效,在日志中找不到 ORDER 语句。

将 created_at 字段添加到您的 table。

rails g migration AddTimestampsToCourseUsers created_at:datetime

那么你可以

@product.users.order "course_users.created_at ASC"