0

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?

1
  • Hey Usman, you should just accept one as a solution, to let other people know that you found your solution. Commented Oct 14, 2015 at 16:40

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

1
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')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.