Skip to content

Instantly share code, notes, and snippets.

@xanhast
Created December 4, 2013 18:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xanhast/7792766 to your computer and use it in GitHub Desktop.
Save xanhast/7792766 to your computer and use it in GitHub Desktop.

Confused. I have some code in a migration that only works when I run rake db:rollback db:migrate but not if I run rake db:rollback then rake db:migrate.

Migration:

# ...add_latitude_and_longitude_to_organisation.rb
class AddLatitudeAndLongitudeToOrganisation < ActiveRecord::Migration
  def up
    add_column :organisations, :latitude, :float
    add_column :organisations, :longitude, :float

    Organisation.all.each do |organisation|
      valid_postcode = GoingPostal.postcode?( organisation.postcode, "GB")
      if valid_postcode
        organisation.postcode = valid_postcode
        organisation.geocode
        organisation.save # => true
      else
        organisation.update_column :postcode, nil
      end
    end
  end

  def down
    remove_column :organisations, :latitude
    remove_column :organisations, :longitude
  end
end

# ...models/organisation.rb
class Organisation < ActiveRecord::Base
  geocoded_by :postcode
  after_validation :geocode, :if => Proc.new {|e| e.postcode_changed?}

  # ...
end

It gets even weirder, I have the identical setup where I've added this to the User model and it works always. The only difference I can see in callbacks is that organisation is indexed by sunspot solr, however it's exactly the same when I remove solr from organisation.

organisation.save returns true, there are no errors on the object and no exceptions raised. I've printed the postcode etc, it's all sane and as expected.

organisation.latitude before the save returns the lat, but it isn't in the database! organisation.reload.latitude after the save returns nil. EXCEPT when I do rake db:rollback db:migrate... wtf.

The 'GoingPostal' gem is aptly named right now...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment