我有一个Match
和User
模型,它们之间有一个has_and_belongs_to_many。
如何根据创建MatchUser
关联的时间而不是创建User
本身的时间检索match.users.first
和match.users.second
?
您首先不希望使用has_and_belongs_to_many
。has_and_belongs_to_many
关系是无头的-不存在联接模型。联接表中唯一使用过的列是两个外键。即使向联接表中添加了created_at
列,也无法访问它或使用它对记录进行排序。AR无论如何都不会设置时间戳。
虽然你可以假设has_and_belongs_to_any关联的顺序与插入的记录的顺序相同,但你不能真正对其进行排序。
您想要使用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
然后,您可以通过以下方式订购关联:
match.users.order("user_matches.created_at DESC")
match.users.first
将通过:id返回第一个用户。
如果你想让它按created_at排序,那么你必须做一些类似的事情
user_id = matches_users.where(match_id: match.id).first.user_id
user.find(user_id)
希望这就是你所看到的。