Question

I have an asset model class and it has different sizes using paperclip 3.5.2:

class AssetSerializer < ActiveModel::Serializer
  attributes :id, :asset # works fine
  # would like to output small but don't seem to be able to
  #attributes :id, :asset, :asset(:small) 
end

It's a bit confusing because Paperclip uses the name class and the model is called class (ok really confusing). I get the following error:

/Users/jt/repos/rails/app/serializers/asset_serializer.rb:2: syntax error, unexpected '(', expecting keyword_end
  attributes :id, :asset, :asset(:small)

It clearly doesn't like the argument passed to asset

Was it helpful?

Solution 3

Just wrote methods on the class and called them like...

class Asset < ActiveRecord::Base
  ...
  def asset_small
    asset.url(:small)
  end

  def asset_original
    asset.url
  end
  ...
end

...

class AssetSerializer < ActiveModel::Serializer
  attributes :id, :asset_small, :asset_original
end

and that worked fine.

OTHER TIPS

You can just add a custom attribute inside of the serializer

They have an example in the docs https://github.com/rails-api/active_model_serializers#attributes

Here's what you would use given your example.

class AssetSerializer < ActiveModel::Serializer
  attributes :id, :asset, :asset_small

  def asset_small
    object.asset.url(:small)
  end
end

Im not sure that it work, but try this: Or probably play around define_method to override :asset.

class AssetSerializer < ActiveModel::Serializer
  attributes :id, :asset 

  self._attributes.each do |attribute, value|
    define_method(attribute) do
      object.read_attribute(attribute)
    end
  end
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top