Haseeb Ahmad
Haseeb Ahmad

Reputation: 8740

Sort data in ruby on rails

Association is like

class User < ActiveRecord::Base

has_many :products
has_many :ratings

I want to sort products according to user ratings. Let suppose I want to sort all those product whose ratings is greater than 4. I cant find any way to do that.

I do something like

User.joins(:ratings).where("ratings.rate > ?", 4).includes(:ratings)

From that I get all user whose ratings is greater than 4 but how join with product and sort them?

Upvotes: 0

Views: 1232

Answers (2)

nsave
nsave

Reputation: 984

User.joins(:ratings).where("ratings.rate > ?", 4).order('ratings.rate')

And if you want to find associated products then this should work:

Product.joins(user: :ratings).where("ratings.rate > ?", 4).order('ratings.rate')

Upvotes: 1

Abhinay
Abhinay

Reputation: 1816

User.joins(:ratings).where("ratings.rate > ?", 4).order('ratings DESC')

I am not sure what includes(:ratings) doing at the last. Should just use something like this and it should probably work:

User.includes(:ratings).where("ratings.rate > ?", 4).order('ratings DESC')

Reference: issue in order clause and limit in active record

Upvotes: 3

Related Questions