【问题标题】:Setting a rails active record default_scope order that depends on an associated model设置依赖于关联模型的 rails 活动记录 default_scope 顺序
【发布时间】:2012-05-28 19:50:13
【问题描述】:

我有两个模型,帖子和评论。每个帖子都有很多cmets。我想按评论最近的帖子排序我的帖子。

我正在尝试在我的 Post 模型上设置 default_scope,如下所示:

default_scope :order => 'posts.comments.last.updated_at DESC'

。 .但是当我尝试这样做时,我得到了一个 PGError。我该怎么办?

【问题讨论】:

    标签: ruby-on-rails postgresql activerecord associations


    【解决方案1】:

    使用这个

    default_scope.joins(:comments).find(:all, :order => 'comments.updated_at DESC', :group => 'id')
    

    这对我有用。

    【讨论】:

      【解决方案2】:

      试试这个:

      default_scope :joins => :comments, :order => 'comments.updated_at DESC', :group => 'id'
      

      【讨论】:

      • 这可行,但会导致重复。 'cmets.last.updated_at DESC' 也不起作用。有没有办法调用最后或强制唯一性?
      • 使用 ":group => 'id'",我得到 'PGError: ERROR: column reference "id" is ambiguous' 如果这很重要,当我打电话给帖子时,它来自另一个模型与帖子相关联:'deal.posts'
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多