【问题标题】:Rails 5 - How to sort has_many associations list?Rails 5 - 如何对 has_many 关联列表进行排序?
【发布时间】:2018-01-08 10:41:37
【问题描述】:

在 rails 5 和 postgresql 中,我想根据 created_at: :desc 对列表进行排序。

模型结构是这样的, 模型/review.rb

has_many :comments
has_many :commented_users, :through=>:comments, :source=>:user

在视图中,我想根据created_at (DESC) 日期显示用户列表,该字段来自comments

控制器查询就像,

review = Review.find_by_id(params[:id])
comments = review.commented_users

如果我为review.commented_users 提供order,那么显然它将对User 进行排序,我如何根据Comment 对用户进行排序?

审核字段是,

=> #<Review id: nil, user_id: nil, content: nil, created_at: nil, updated_at: nil>

评论字段是,

=> #<Comment id: nil, review_id: nil, user_id: nil, created_at: nil, updated_at: nil>

用户字段是,

=> #<User id: nil, email: "", created_at: nil, updated_at: nil, first_name: nil, last_name: nil, inactive: false, password_updated_at: nil, active: true, reviews_count: 0, notification_seen_at: nil, deleted_at: nil, status: "pending">

请帮我解决这个排序问题,我是postgresql的新手

【问题讨论】:

  • 这里又是id 将采用User 模型而不是Comment
  • 关联有问题
  • 你能显示你的评论字段和关系吗?
  • 问题已更新
  • @ShruthiR 我认为commented_users 也会返回users 数组,对吗?

标签: ruby-on-rails ruby postgresql sorting ruby-on-rails-5


【解决方案1】:

请从您的关联中删除不同

has_many :commented_users, through: :comments, source: :user

您可以使用以下代码验证用户的唯一性

validates :review_id, uniqueness: {scope: :user_id}

最后尝试下面的查询,以获取按创建的评论表排序的记录。

Review.includes(comments: :user).find_by_id(params[:id]).commented_users.order("comments.created_at")

【讨论】:

  • 我怎样才能在没有任何关系的情况下获得commented_users?现在我得到它基于comments
  • 你想要什么,cmets 还是用户?
  • 您必须发布正确的问题。让我再检查一次
  • 我想要基于评论日期的用户。应首先显示最新评论的用户。
  • 能否请您发布您在 cmets 模型中使用的关联?
猜你喜欢
  • 1970-01-01
  • 2020-04-16
  • 2010-10-18
  • 1970-01-01
  • 1970-01-01
  • 2016-04-02
  • 1970-01-01
  • 2016-06-04
  • 1970-01-01
相关资源
最近更新 更多