algolia / algoliasearch-rails

AlgoliaSearch integration to your favorite ORM
MIT License
410 stars 118 forks source link

Indexing Carrierwave uploads URLs #275

Open Spone opened 6 years ago

Spone commented 6 years ago

Hi,

we have a model with an image (uploaded with Carrierwave and stored on Cloudinary). We tried to index the URL of the image (which is uploaded at the same time as creating the model), but all we got was null...

algoliasearch do
   attribute :name, :description # [...]
   attribute :photo do
     self.photo.url
     # or
     self.photo_url
     # (neither work)
   end
 end

We had to do this to make it work:

algoliasearch do
   attribute :name, :description # [...]
   attribute :photo do
     self.photo.metadata[‘url’]
   end
 end

I wondered if the issue was coming from the order of the callbacks on the model.

Carrierwave relies on all these callbacks: https://github.com/carrierwaveuploader/carrierwave#skipping-activerecord-callbacks

Do you have any idea why?

redox commented 6 years ago

Oh interesting, never heard about that.

Could either be related to callbacks (still, I feel like this won't impact ours; the library is just wrapping the existing) or maybe to scoping (we use Model.unscoped do ... end at some point).

Could you check whether the following code is working OK:

YourModel.unscoped do
  your_instance.photo.url
end
Spone commented 6 years ago

We just tried that, it does not change anything.

We actually had to modify the snippet to handle both the create and reindex cases.

attribute :photo do
   # when no photo has been added to the model
   return nil if self.photo.nil?
   # when we are uploading a photo on create, it seems to be the only way we can access the URL
   return self.photo.metadata[‘url’] if self.photo.metadata.present?
   # when the photo is already uploaded, we can just access it this way
   self.photo.url
end

But it's still more complicated than it should be...