简体   繁体   English

如何按嵌套属性排序嵌套属性

[英]how to order nested attribute by nested attribute

I have Users who have Profiles. 我有拥有个人资料的用户。 I can display the Profiles like this: 我可以这样显示个人资料:

@profiles.each do |p|
  puts p.user.last_name + " " + p.user.first_name
end 

I don't know how to order by last_name, because it's a nested attribute and not part of the Profiles table directly. 我不知道如何按last_name进行排序,因为它是一个嵌套属性,不是直接在Profiles表中的一部分。 My Users model orders correctly, but not when I'm calling the user name through his profile. 我的用户可以正确地建模订单,但是不能在我通过用户个人资料调用用户名时建模。 Thanks for any help. 谢谢你的帮助。 Should I make a "profiles_helper.rb" file or should I order in the view? 我应该制作“ profiles_helper.rb”文件还是应该在视图中订购?

You can use group_by to convert profiles to array, and then you can use sort_by method to sort based on last_name 您可以使用group_byprofiles转换为数组,然后可以使用sort_by方法基于last_name进行排序

profiles = @profiles.group_by{|p| p.user.last_name}
result = profiles.sort_by{|last_name, profiles| last_name}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM