Sushant Bajracharya
Sushant Bajracharya

Reputation: 65

custom ordering activerecord data in rails

I have 3 courses A(july 1), B(july 2), C(july 3).A and B is rated 4 and C is rated 5.

I want to order the course like this

C should come first because it was created latest and it has higher rating than others.

A should come second because it was created first than B

I cant use order because it wont give me what i need. any way to fix this?

Here is how i am fetching the data

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

code

[
#<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>,

Upvotes: 0

Views: 871

Answers (2)

Gagan Gami
Gagan Gami

Reputation: 10251

Try:

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

Upvotes: 1

Nimish Gupta
Nimish Gupta

Reputation: 3175

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

This will sort first on created_at and if two records have same created_at the will sort on the basis of rating

Upvotes: 0

Related Questions