Ruby on rails 活动模型序列化器和不同尺寸的回形针
我有一个资产模型类别,它使用回形针3.5.2具有不同的尺寸:Ruby on rails 活动模型序列化器和不同尺寸的回形针,ruby-on-rails,ruby-on-rails-3.2,paperclip,active-model-serializers,Ruby On Rails,Ruby On Rails 3.2,Paperclip,Active Model Serializers,我有一个资产模型类别,它使用回形针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 它显然不喜欢传递给asset的参数,我不确定
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
它显然不喜欢传递给asset的参数,我不确定它是否有效,但请尝试以下方法: 或者可能使用define_方法来覆盖: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
类AssetSerializerclass 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
class资产
这很好。您只需在序列化程序中添加一个自定义属性即可 他们在文档中有一个例子 以下是您将使用的示例
class AssetSerializer < ActiveModel::Serializer
attributes :id, :asset, :asset_small
def asset_small
object.asset.url(:small)
end
end
类AssetSerializerclass AssetSerializer < ActiveModel::Serializer
attributes :id, :asset, :asset_small
def asset_small
object.asset.url(:small)
end
end