I have an encrypted field that uses a before_save (etc) callback to
accomplish the field encryption. It works right now with one key for
the application.
I have a model where users belong to groups (groups have many users)
and each group has a unique key. I want to grab the group “key” during
the callback. When I try to add “key = model.group.key”, I get an
error: NoMethodError: undefined method `key’ for nil:NilClass
I assumed that the “model” would resolve to the user model and that I
could follow the relation into group and grab the “key”. I works in
the console by hand once I assign the find results to a variable.
def before_save(model)
unless model[@field].blank?
key = model.class.encryption_key
goo = model.group.key # see if I can see the "key"
Rails.logger.debug("group key: #{goo}") # log it
model[@field] = encrypt(model[@field], key, @options)
end
end
I can get the proper text by using:
goo = Group.find(model[‘group_id’]).key
Is there a “cleaner” way to express this?