自定义在rails中订购activerecord数据

时间:2017-07-12 05:45:15

标签: ruby-on-rails ruby

我有3门A(7月1日),B(7月2日),C(7月3日).A和B评级为4,C评级为5.

我想订购这样的课程

C应该首先出现,因为它是最新创建的,并且它的评级高于其他。

A应该排在第二位,因为它是先于B

创建的

我无法使用order,因为它不会给我我需要的东西。有什么方法可以解决这个问题吗?

以下是我如何获取数据

@courses.order('updated_at DESC, average_rating DESC')

[
#<Course:0x00000009f3c128
  id: 6,
  tutor_id: 2,
  course_name: "name",
  course_subtitle: "sub",
  course_description: "<p>test</p> test\r\n",
  video_link: "https://www.youtube.com/watch?v=UVrQcieqD0U",
  course_language: "German",
  course_image: "finalse.png",
  created_at: Tue, 11 Jul 2017 05:03:03 UTC +00:00,
  updated_at: Tue, 11 Jul 2017 08:47:03 UTC +00:00,
  status: "accepted",
  average_rating: 2.5,
  rated_time: nil>,
 #<Course:0x00000008139608
  id: 7,
  tutor_id: 2,
  course_name: "another",
  course_subtitle: "another subtuitle",
  course_description: "<p>course descrition</p>\r\n",
  video_link: "https://www.youtube.com/watch?v=uaTeZA-Gj7s",
  course_language: "Chinese",
  course_image: nil,
  created_at: Tue, 11 Jul 2017 10:40:45 UTC +00:00,
  updated_at: Tue, 11 Jul 2017 10:41:06 UTC +00:00,
  status: "accepted",
  average_rating: 2.5,
  rated_time: nil>,
 #<Course:0x0000000813bea8
  id: 8,
  tutor_id: 2,
  course_name: "asfas",
  course_subtitle: "were",
  course_description: "<p>asdfsadf</p>\r\n",
  video_link: "https://www.youtube.com/watch?v=xGytDsqkQY8",
  course_language: "English",
  course_image: nil,
  created_at: Wed, 12 Jul 2017 03:53:26 UTC +00:00,
  updated_at: Wed, 12 Jul 2017 04:32:33 UTC +00:00,
  status: "accepted",
  average_rating: 1.0,
  rated_time: nil>,

2 个答案:

答案 0 :(得分:1)

尝试:

Course.all.order("average_rating DESC, created_at ASC")

答案 1 :(得分:0)

Course.order({ created_at: :desc, rating: :desc })

这将首先在created_at上排序,如果两个记录具有相同的created_at,则会根据评分进行排序