Search code examples
ruby-on-railsformsvirtual-attribute

use multiple virtual attribute form inputs to update a single model attribute


I have the following virtual attributes within my model:

attr_accessor :city, :zip, :street, :suite

In the new/edit form, I have form fields for each of these attributes. I can convert these four attributes into a single address_id with a method we'll call address_lookup. I only need to store the address_id in the model. What's the basic approach to cleanly handle this in the create/update controller actions, and (if necessary) the model? It's a little over my head.


Solution

  • Simplest is to add in a before_save callback, we'll use the changed array to check whether any of the attributes we're interested in have changed before we do our lookup:

    before_save :set_address
    
    def set_address
      if address = Address.find_or_create_by( city: city, zip: zip, street: street, suite: suite)
        self.address = address
      end
    end