3

我有一个资产模型类,它使用回形针 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)

它显然不喜欢传递给资产的论点

4

3 回答 3

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
于 2014-01-15T18:47:23.567 回答
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

效果很好。

于 2014-01-07T03:29:01.067 回答
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
于 2014-01-07T02:56:09.093 回答