【问题标题】:rails: sort a has_many using :order is not working due to order by timestamprails:使用 :order 对 has_many 进行排序由于时间戳排序而无法正常工作
【发布时间】:2012-12-20 15:04:28
【问题描述】:

我有一个 Rails 模型,可以说 具有 a 的用户与 Post 有很多关系。 Post 包含一个名为 position 的属性,用于存储位置(acts_as_list gem)。位置存储用户帖子列表中的位置(顺序不是由于创建/修改帖子)。 此外,Post 存储了时间戳(t.timestamps 在迁移中)

所以我在 User.rb 中定义了以下内容:

has_many :post, :order => "position", :dependent => :destroy

但是,当我执行User.first.posts 时,帖子不是按位置排序的。 我已经检查过,正在查询的 sql 包含以下内容:

ORDER BY post.created_at DESC, position

所以 created_at 仍在使用中。

如何按位置排序而不使用 created_at 属性?

提前致谢!

解决方案 我在 Post 中定义了一个默认范围,它创建了不想要的订单。

问题解决了

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 acts-as-list


    【解决方案1】:

    您可以使用default scope

    class Post < ActiveRecord::Base
      scope :by_position, order("position ASC")
      default_scope by_position
      #...
    end
    

    那么@user.posts 应该返回一个按位置(ASC)排序的列表。

    此外,以下内容应该对您有用:(post 上的复数)

    has_many :posts, :dependent => :destroy, :order => "posts.position ASC"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-14
      • 1970-01-01
      • 2021-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多