【问题标题】:Order HABTM associations by created_at on the association instead of the object按关联而不是对象上的 created_at 对 HABTM 关联进行排序
【发布时间】:2018-12-02 12:39:55
【问题描述】:

我有一个 Match 和 User 模型,它们之间有一个 has_and_belongs_to_many。

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

【问题讨论】:

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


    【解决方案1】:

    您一开始就不想使用has_and_belongs_to_many。 has_and_belongs_to_many 关系是无头的 - 没有连接模型。连接表上唯一使用的列是两个外键。即使您在连接表中添加了created_at 列,也无法访问它或使用它来对记录进行排序。而且 AR 也不会设置时间戳。

    虽然您可以假设 has_and_belongs_to_many 关联的排序顺序与插入的记录的顺序相同,但您无法真正对其进行排序。

    您想使用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")
    

    【讨论】:

      【解决方案2】:
      match.users.first
      

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

      如果您想通过 created_at 对其进行排序,那么您必须执行类似的操作

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

      希望这就是你所看到的。

      【讨论】:

        猜你喜欢
        • 2012-01-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-12-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多