【问题标题】:Using ActiveModel::Serializer in Rails - JSON data differs between json and index response在 Rails 中使用 ActiveModel::Serializer - JSON 数据在 json 和 index 响应之间存在差异
【发布时间】:2012-11-02 06:57:33
【问题描述】:

我正在使用active_model_serializers gem 来控制序列化数据,并看到一些奇怪的行为。我的代码如下所示:

模型和序列化器

class User
  include Mongoid::Document
  field :first_name, :type => String
  field :last_name,  :type => String

  def full_name
    first_name + " " + last_name
  end
end

class UserSerializer < ActiveModel::Serializer
  attributes :id, :first_name, :last_name, :full_name
end

控制器

class UsersController < ApplicationController
  respond_to :json, :html

  def index
    @users = User.all
    respond_with @users
  end
end

视图(app/views/users/index.html.erb)

...
<script type="text/javascript">
  $(function(){
    // using a backbone collection to manage data
    App.users = new App.Collections.Users(<%= @users.to_json.html_sage %>);
  });
</script>

现在,当我渲染视图时,我发现我的数据中缺少 full_name 属性(通过模型中的方法生成):

{
  "id": 2,
  "first_name": "John",
  "last_name": "Doe"
}

当我访问/users.json(我的routes.rb 文件中有resources :users)时,我看到了正确的JSON:

{
  "id": 2,
  "first_name": "John",
  "last_name": "Doe",
  "full_name": "Jonn Doe"
}

我看不出我做错了什么——任何输入都会有所帮助。谢谢。

【问题讨论】:

  • 请标记您使用的语言,而不是诸如“mismtach”之类的无用标签 - 这次我已经为您完成了
  • 没问题 - 只是一个友好的提醒 :) 它改进了语法着色并会吸引更多的关注
  • 还没有。如果你有什么,请告诉我。

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


【解决方案1】:

@Gagan 这对我有用:

App.users = new App.Collections.Users(<%= ActiveModel::ArraySerializer.new(@users).to_json.html_safe %>);

【讨论】:

    【解决方案2】:

    您没有在 HTML 视图中使用序列化程序。试试这个:

    App.users = new App.Collections.Users(<%= UserSerializer.new(@users).to_json.html_safe %>);

    原因是序列化器是在respond_with 方法中提取的,序列化器执行not overwrite 你的.to_json 方法。

    【讨论】:

    • 我也有同样的问题,但是当我应用您的解决方案时,它抛出异常说“#<:relation:0x007fdb18ea4ef8> 的未定义方法 `read_attribute_for_serialization'”。是不是由于gem版本。我正在使用 AMS 0.7.0 和 json 1.7.7 gems。
    • @Gagan 我有同样的问题,缺少 read_attribute_for_serialization(注意我没有使用 Mongoid,但没有持久化 ActiveModel),我必须将它添加到我的类中:包括 ActiveModel::Serialization。成功了。
    • 除了添加包含 ActiveModel::Serialization 之外,我还必须确保在我的 gem 文件中我使用的是 0.8.1 of AMS gem 'active_model_serializers', '~> 0.8.1'
    猜你喜欢
    • 2016-09-27
    • 1970-01-01
    • 2015-08-05
    • 1970-01-01
    • 1970-01-01
    • 2014-01-15
    • 1970-01-01
    • 2016-02-04
    • 1970-01-01
    相关资源
    最近更新 更多