wendigooor wendigooor - 2 months ago 12
SQL Question

Rails order by association field

I have the following models

class User
attr_accesible :first_name, :phone_number
has_one :user_extension
end

class UserExtension
attr_accessible :company, :user_id
belongs_to :user
end


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

@user.user_extension.company


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

Edit:

I should provide more information about this models.

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

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


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


on

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


i also get

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


Resolved
Have problems with my bd, all joins works fine.

Answer

Try this:

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

I think you need at order: user_extensions, not user_extension