Tony Vincent
Tony Vincent

Reputation: 14372

Rails - sort by parents attribute

I have the following 2 tables

Table "public.friendships"

   Column   |            Type             |
------------+-----------------------------+
 id         | integer                     |
 user_id    | integer                     |
 friend_id  | integer                     |
 created_at | timestamp without time zone |
 updated_at | timestamp without time zone |

Table "public.users"

         Column         |            Type             |
------------------------+-----------------------------+
 id                     | integer                     |
 encrypted_password     | character varying(128)      |
 password_salt          | character varying(128)      |
 email                  | character varying(255)      |
 .
 .
 .
 .

associations between these tables are as follows

#user.rb
has_many :friendships, class_name: 'Friendship', :foreign_key => 'user_id', :dependent => :destroy

#friendship.rb
belongs_to :user, :class_name => 'User'
belongs_to :friend, :class_name => 'User', :foreign_key => 'friend_id'

I am trying to find all friendships of a user

@user = current_user
@friendships = @user.friendships

Everything works great. But I want to list all friends of the current user, sorted in alphabetical order of their first_name. I tried

 @friendships = @user.friendships.order(:first_name)

of course it doesn't work. What is the right way of doing this?

Upvotes: 1

Views: 372

Answers (1)

Eyeslandic
Eyeslandic

Reputation: 14910

You can put an order clause on the has_many

has_many :friendships, -> { joins(:user).order('users.first_name') }, foreign_key: 'user_id', dependent: :destroy

Then this will work automatically

@friendships = @user.friendships

Upvotes: 2

Related Questions