Accessing relationships during call backs

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?

On Fri, Nov 5, 2010 at 9:57 AM, dwormuth [email protected]
wrote:

could follow the relation into group and grab the “key”. I works in

I can get the proper text by using:

goo = Group.find(model[‘group_id’]).key

Is there a “cleaner” way to express this?

You should be using self instead of model.


Erol M. Fornoles
http://github.com/Erol
http://twitter.com/erolfornoles
http://ph.linkedin.com/in/erolfornoles

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs