在Rails中使用ActiveModel :: Serializer – JSON数据在json和index响应之间有所不同
我正在使用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
view(app / views / users / index.html.erb)
... $(function(){ // using a backbone collection to manage data App.users = new App.Collections.Users(); });
现在,当我渲染视图时,我看到我的数据中缺少full_name
属性(通过模型中的方法生成):
{ "id": 2, "first_name": "John", "last_name": "Doe" }
当我访问/users.json
(我有resources :users
我的routes.rb
文件中的resources :users
)时,我看到了正确的JSON:
{ "id": 2, "first_name": "John", "last_name": "Doe", "full_name": "Jonn Doe" }
我看不出我可能做错了什么 – 任何输入都会有所帮助。 谢谢。
您没有在HTML视图中使用序列化程序。 试试这个:
App.users = new App.Collections.Users(<%= UserSerializer.new(@users).to_json.html_safe %>);
原因是在.to_json
方法中拾取了序列化程序,序列化程序不会覆盖 .to_json
方法。
@Gagan这适合我:
App.users = new App.Collections.Users(<%= ActiveModel::ArraySerializer.new(@users).to_json.html_safe %>);
- 使用active_model_serializers序列化深层嵌套关联
- ActiveModel :: Serializer无法正常工作
- 使用Rspec测试ActiveModel :: Serializer类
- ActiveModel :: Serializers Gem – Versioned API命名空间问题
- 使用active_model_serializers序列化权限(例如CanCan)
- 更改活动模型序列化器默认适配器
- 如何在active_model_serializers中执行预先加载
- 使用active-model-serializers错误地为act-as-taggable标签加载JSON
- 活动模型序列化器和自定义JSON结构