通过在关联上而不是对象上的created_at对HABTM关联进行排序

时间:2018-12-02 12:39:56

标签: ruby-on-rails activerecord ruby-on-rails-5 has-and-belongs-to-many

我有一个MatchUser模型,它们之间有一个has_and_belongs_to_many。

如何根据创建match.users.first 关联的时间而不是根据创建match.users.second本身的时间来检索MatchUserUser创建了吗?

2 个答案:

答案 0 :(得分:1)

您首先不想使用bitstringhas_and_belongs_to_many关系是无脑的-没有联接模型。联接表上曾经使用过的唯一列是两个外键。即使您在联接表中添加了has_and_belongs_to_many列,也无法访问它或使用它对记录进行排序。而且AR也不会设置时间戳。

虽然您可以假设has_and_belongs_to_many关联的排序顺序与插入记录的顺序相同,但您实际上并不能对其进行排序。

您要使用created_at,该模型使用模型来连接两条记录:

has_many through:

然后您可以通过以下方式订购关联:

class User < ApplicationRecord
  has_many :user_matches
  has_many :matches, through: :user_matches
end

class Match < ApplicationRecord
  has_many :user_matches
  has_many :users, through: :user_matches
end

class UserMatch < ApplicationRecord
  belongs_to :user
  belongs_to :match
end

答案 1 :(得分:-1)

match.users.first

将通过:id返回第一个用户。

如果要按created_at排序,则必须执行类似的操作

user_id = matches_users.where(match_id: match.id).first.user_id
user.find(user_id)

希望这就是您要查看的内容。