【问题标题】:How this attribute with an underscore in my model get convert to dash-separated words?我的模型中带有下划线的这个属性如何转换为破折号分隔的单词?
【发布时间】:2018-09-18 16:23:14
【问题描述】:

我有一个带有模型Book 实例的序列化程序。

我把我的serializer 实例给了

ActiveModelSerializers::Adapter::JsonApi.new(serializer) 类,其中serializer 是我的实例。

上面的方法调用返回了这个

#<ActiveModelSerializers::Adapter::JsonApi:0x000000000b515b48 @serializer=#<BookSerializer:0x0000000008496a30 @object=#<Book id: 8, type: "Book", created_at: "2018-09-18 10:25:55", updated_at: "2018-09-18 10:25:55">, @instance_options={:scope}, @root=nil, @scope=nil, @serializer_class=BookSerializer, @attributes={:id=>8, :email=>"random@exam.com", :author=>"user1", :created_at=>Tue, 18 Sep 2018 10:25:55}, @_config={}>, @instance_options={}, @include_directive=#<JSONAPI::IncludeDirective:0x000000000b515aa8 @hash={}, @options={:allow_wildcard=>true}>, @fieldset=#<ActiveModel::Serializer::Fieldset:0x000000000b5159e0 @raw_fields={}>> 

然后我尝试在 Adapter 类实例上调用serializable_hash,如下所示

ActiveModelSerializers::Adapter::JsonApi.new(serializer).serializable_hash 上面的调用返回了这个

{:data=>{:id=>"8", :type=>"books", :attributes=>{:email=>"random@exam.com", :author=>"user1", :"created-at"=>Tue, 18 Sep 2018 10:25:55 UTC +00:00}, :relationships=>{:"book"=>{:data=>{:id=>"15", :type=>"books"}}}}}

以上返回的数据已将created_at转换为created-at

当我在适配器类实例中调用 serializable_hash 时会发生什么?

【问题讨论】:

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


    【解决方案1】:

    可序列化哈希返回对象的序列化哈希。

    book = Book.new
    book.title = 'Legends'
    book.content  = 'Once upon a time, in a far away galaxy'
    book.serializable_hash # => {"title"=>"Legends", "content"=>"Once upon a time, in a far away galaxy"}
    

    参考检查this out

    【讨论】:

    • 我明白了,但是为什么上面的属性会从created_at变成created-at
    • 我相信,JsonApi 使用的标准是dashes,而不是underscores。我知道的唯一解决方法是,config 目录下有文件active_model_serializers.rb 吗?在文件ActiveModel::Serializer.config.adapter = ActiveModel::Serializer::Adapter::JsonApiActiveModelSerializers.config.key_transform = :underscore中添加以下行
    • 是的。在配置文件下,并在其中包含这一行 ActiveModelSerializers.config.adapter = :json
    • 您需要将ActiveModelSerializers.config.key_transform = :underscore添加到active_model_serializers.rb
    猜你喜欢
    • 2021-02-06
    • 1970-01-01
    • 2017-08-18
    • 2017-08-28
    • 2013-04-29
    • 1970-01-01
    • 2011-12-24
    • 1970-01-01
    • 2016-09-30
    相关资源
    最近更新 更多