在 Rails 5 和 postgresql
中,我想根据 created_at: :desc
对列表进行排序。
模型结构就像, 模型/评论.rb
has_many :comments
has_many :commented_users, :through=>:comments, :source=>:user
在 View 中,我想显示基于 created_at (DESC)
日期的用户列表,该字段来自 comments
表
Controller 查询就像,
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
最佳答案
请从您的关联中删除不同
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")
关于ruby-on-rails - Rails 5 - 如何对 has_many 关联列表进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48148608/