Search code examples
ruby-on-railsencryptionattr-encrypted

How to sort on a field that is encrypted using the attr_encrypted gem


I am currently using attr_encrypted gem to encrypt content so that only users that have a certain key can see portions of documents available to a broader group. Everything works fine until I try to sort the list on one of the encrypted fields. I've read the documentation several times and experimented several way to no avail.

In the CommunityMember model:

attr_encrypted :last_name, :key => :encryption_key

In the controller I have tried

@list = CommunityMember.order("last_name")
AND
@list = CommunityMember.order("encrypted_#{last_name}")
AND
@list = CommunityMember.order("encrypted_#{'last_name'}")

None produced the desired result. Thanks for your help.

Jay


Solution

  • You can use the sort_by method

    @list = CommunityMember.all.sort_by(&:last_name)