stephskardal / rails_admin_import

Rails Admin Import functionality
http://www.endpoint.com/
MIT License
160 stars 122 forks source link

Configurable downcasing association fields prior to before_import_save #63

Closed dmitrypol closed 6 years ago

dmitrypol commented 8 years ago

I am thinking of before_import_associate and after_import_associate callbacks where developer can do custom pre-processing before associations occur. But I wanted to check in and see if anyone had better ideas?

CSV: amount,user 10,Bob.smith@example.com

But user.email in the DB is bob.smith@example.com so it doesn't find association.

When I do record[:user].downcase in before_import_save it modifies the record, but the association lookup already happened prior to that.

class User
  field :email
  has_many :purchases
  rails_admin do
    import do
      mapping_key :email
    end  
  end
end
class Purchase
  field :amount
  belongs_to :user
  validates :user, presence: true
  def before_import_save(record)
  # this doesn't work as by this point association already failed
  # self.user = User.where(email: record[:user].downcase).first
  end
end
monkbroc commented 8 years ago

I like the idea of having more escape hatches from the default behavior in the form of hooks.

I'm thinking one hook called import_find_or_create(record) to customize the find_or_create behavior. This would allow you to fix your current issue. https://github.com/stephskardal/rails_admin_import/blob/df0b6429430eafb62e2331d7e6af6751fb33fc19/lib/rails_admin_import/importer.rb#L179

Another hook would be needed to generalize the association fetching (for the multi-tenant account/email case). I'm not sure what that would look like. https://github.com/stephskardal/rails_admin_import/blob/df0b6429430eafb62e2331d7e6af6751fb33fc19/lib/rails_admin_import/import_model.rb#L73

monkbroc commented 6 years ago

I added additional hooks that would allow implementing better custom logic