Jerome
Jerome

Reputation: 6217

geocode on one of multiple attribute changes

with Rails geocoder gem the geocoding is run as a callback on the model. To avoid hitting uselessly the geocoding API service, this callback needs to be conditional on one of the key attributes to forming an address for geocoding; these are saved to the database (address, municipal_id, postcode, region_id, nation_id).

Defining a virtual attribute combining those values

def inserted_address
  [self.address, self.municipal.name, self.postcode, self.region.try(:name), self.nation.name].compact.join(', ')
end

will not play with ActiveRecord's dirty module, as it is apparently only acting upon database-written values. So obj.inserted_address.changed? is not a solution. But the following method on the class

after_validation :geocode, if: ->(obj){ obj.inserted_address.present? and (obj.address.changed? or obj.postcode.changed? or obj.municipal_id.changed?) }

returns a complaint that undefined method 'changed?' for "my street, 114":String

How can this statement be then composed?

Upvotes: 0

Views: 77

Answers (0)

Related Questions