【问题标题】:Active Model Serializer and Paperclip different sizesActive Model Serializer 和 Paperclip 不同尺寸
【发布时间】:2014-01-07 02:48:46
【问题描述】:

我有一个资产模型类,它使用回形针 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 使用名称 class 而模型称为 class(好吧真的很混乱)。我收到以下错误:

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

它显然不喜欢传递给资产的参数

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3.2 paperclip active-model-serializers


    【解决方案1】:

    你可以在序列化器中添加一个自定义属性

    他们在文档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
    

    【讨论】:

      【解决方案2】:

      我不确定它是否有效,但试试这个: 或者可能使用 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
      

      【讨论】:

        【解决方案3】:

        只是在类上写了方法,然后像...一样调用它们

        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
        

        效果很好。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2014-02-20
          • 1970-01-01
          • 2014-09-20
          • 2017-01-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多