Order area in Rails 3.2.11 by has_one association

In my Rails 3.2.11 application, I have a scope that I am trying to order based on its associated attribute. In my case, I have a user model and a profile model. User profile has_one and my scope are in an attribute in the profiles table. Here's the scope:

In User.rb

:

def self.with_default_show
  joins(:profile).where("profiles.show_all = true")
end

      

However, the problem I'm running into is trying to declare the order. For example, running:

joins(:profile).where("profiles.show_all = true").order("profiles.first_name DESC")

      

Gives me an error:

PG::Error: ERROR:  for SELECT DISTINCT, ORDER BY expressions must appear in select list

      

I know I can do it .order("2")

, but this brings up the second column in my Users table, not my Profiles table. How do I correctly order the order in this area by the .first_name profile?

+3


source to share


2 answers


The resulting work was a combination of the two answers above:

def self.with_default_show
  joins(:profile)
  .where(profiles: {show_all: true})
  .select('users.*, profiles.first_name')
  .order('profiles.first_name')
end

      



Sorted as I hoped.

0


source


ORDER BY clause can only be applied after DISTINCT has been applied.

Also you must explicitly select for the order you are ordering.



User.select('profiles.*, profiles.first_name')
       .joins(:profile)
       .where("profiles.show_all = true")
       .order("profiles.first_name DESC")

      

As shown above, for your query to return profile attributes, you must also explicitly select them.

+2


source







All Articles