wendigooor wendigooor - 1 year ago 118
SQL Question

Rails order by association field

I have the following models

class User
attr_accesible :first_name, :phone_number
has_one :user_extension

class UserExtension
attr_accessible :company, :user_id
belongs_to :user

I have table which contains all users. And I need to sort this table by first_name, phone_number, company.
With first_name, phone_number I don't have any problems, order works fine, in example

@users = User.order("first_name desc")

, but I also need sort by company and don't know how to do it.

And I can get company name by this way


So i have troubles with sql, which will gave me all users ordered by company.
DB: PostgreSQL.


I should provide more information about this models.

create_table "user_extensions", :force => true do |t|
t.integer "user_id"
t.string "company"

create_table "users", :force => true do |t|
t.string "first_name"
t.string "phone_number"

Also, I tried use join

User.joins(:user_extension).order("user_extension.company desc")

and what i get

User Load (1.6ms) SELECT "users".* FROM "users" INNER JOIN "user_extensions" ON "user_extensions"."user_id" = "users"."id" ORDER BY user_extension.company desc
PG::Error: ERROR: relation "user_extensions" does not exist


User.includes(:user_extension).order("user_extension.company desc")

i also get

PG::Error: ERROR: relation "user_extensions" does not exist

Have problems with my bd, all joins works fine.

Answer Source

Try this:

@users = User.includes(:user_extension).order("user_extensions.company desc")

I think you need at order: user_extensions, not user_extension

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download