我有一个资产模型类,它使用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
这有点令人困惑,因为Paperclip使用了名称类,而模型被称为类(确实令人困惑)。我收到以下错误:
/Users/jt/repos/rails/app/serializers/asset_serializer.rb:2: syntax error, unexpected '(', expecting keyword_end
attributes :id, :asset, :asset(:small)
它显然不喜欢传递给资产的参数
答案 0 :(得分:6)
您只需在序列化程序中添加自定义属性
即可他们在文档https://github.com/rails-api/active_model_serializers#attributes
中有一个示例以下是您的例子。
class AssetSerializer < ActiveModel::Serializer
attributes :id, :asset, :asset_small
def asset_small
object.asset.url(:small)
end
end
答案 1 :(得分:0)
我不确定它是否有效,但试试这个: 或者可能围绕define_method来覆盖: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
答案 2 :(得分:0)
刚刚在课堂上编写方法,并将它们称为......
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
并且工作正常。