简体   繁体   中英

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. 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?

You can use group_by to convert profiles to array, and then you can use sort_by method to sort based on last_name

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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