Adela Tuduce
Adela Tuduce

Reputation: 41

Select query adds attr_encrypted attribute in result even if not requested

I am struggling with an issue with a Rails 5.2.4.1 app. Configuration is the following:

I have a model called Chicken that has 2 attributes: name - which is attr_encrypted and number - which is a normal integer field. Whenever I perform queries to retrieve any other fields except the attr_encrypted one, that still gets attached to the result and it's alway nil:

Chicken.select(:number) => #<ActiveRecord::Relation [#<Chicken id: nil, number: nil, name: nil>]>

Please keep in mind that this is just a test application and the queries that I am trying to execute on the actual app where I have encountered this initially, are more complex.

Is there a way to prevent attr_encrypted from attaching encrypted fields to queries results? Since the current results mean that I have to re-write all the existing queries in the app or add a filter for these types of fields somehow

Upvotes: 1

Views: 307

Answers (1)

Qwertie
Qwertie

Reputation: 6513

This problem was caused by this change to attr_encrypted. As far as I can tell, there isn't any easy way to remove this attribute without modifications to the library but no one actively works on it so that seems unlikely.

The only options as far as I can see are to:

  • Use another library
  • Override the models attributes method to exclude the value (may produce undesirable results). It will still show in other methods active record provides.
  • Deal with it
  • Something else I haven't been able to find

A few ways you can deal with it:

  • Use a library to generate JSON responses for the frontend to only include attributes you want
  • redefine serializable_hash like devise does to remove attributes. (A lot safer than redefining the attributes method itself.

Upvotes: 0

Related Questions