As of right now, i have a model with a has_one_attached :file which i'm serializing with a method as follows.
# app/models/my_model.rb
class MyModel < ApplicationRecord
has_one_attached :file
def file_url
if file.attached?
Rails.application.routes.url_helpers.rails_blob_url(file)
end
end
end
And then in my serializer with activemodel serializer( JSON API format)
type :my_model
attributes(
:file_url
)
Which works just fine, now i'm moving to a has_many_attached :files, and i'm having problems serializing it. i've tried:
class MyModel < ApplicationRecord
has_many_attached :files
def files_url
files.each_With_object([]) do |file, array|
array << Rails.application.routes.url_helpers.rails_blob_url(file)
end
end
then in my app/controller/my_model_controller.rb
def my_model_params
params.require(:my_model).permit(:files => [])
end
And finally, in my serializer, i just call :files_url(instead of file_url, as i used to, which worked with one file), but it won't work:
type :my_model
attributes(
:files_url
)
Any idea on what am i missing? I can't seem to find much useful info regarding serializing has_many_attached. Thanks
Fixed it! it actually works, i was just sending the wrong params to Insomnia.
I replaced
:files => []in my_model_params withfiles: []. And in Insomnia i send each file in themy_model[files][]param.