Rails - 按父母属性排序

时间:2017-05-03 06:51:50

标签: ruby-on-rails activerecord rails-activerecord

我有以下2个表

表" public.friendships"

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

表" public.users"

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

这些表之间的关联如下

#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'

我想找到用户的所有友谊

@user = current_user
@friendships = @user.friendships

一切都很好。但我想列出当前用户的所有朋友,按其first_name的字母顺序排序。我试过了

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

当然它不起作用。这样做的正确方法是什么?

1 个答案:

答案 0 :(得分:1)

您可以在has_many

上添加订单条款
has_many :friendships, -> { joins(:user).order('users.first_name') }, foreign_key: 'user_id', dependent: :destroy

然后这将自动生效

@friendships = @user.friendships