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.
Merge can make the query smaller/saner-looking, and it benchmarked faster for me in Rails 4.x:
@users = User.joins(:user_extension).merge(UserExtension.order(company: :desc))
Try this:
@users = User.includes(:user_extension).order("user_extensions.company desc")
I think you need at order
: user_extensions
, not user_extension
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With