活动模型序列化器

活动模型序列化器

本文介绍了具有虚拟属性的活动模型序列化器-Rails 4的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用RoR制作API,我需要创建一个具有虚拟属性和关联对象的对象.

I am currently making API with RoR, and I need to create an object with virtual attributes and associated object.

问题是当我返回具有虚拟属性的对象时,序列化程序无法启动.

The problem is that serializer does not kick in when I return an object with virtual attribute.

这是foo_controller返回的对象

Here is the returned object from foo_controller

{
    :id=>280,
    :virtual=>"y8st07ef7u"
    :user_id=>280
}

:virtual是虚拟属性,而user_id是关联表的ID-用户.

:virtual is a virtual attribute and user_id is an id of associated table - User.

我的目标是做到这一点

{
    :id=>280,
    :virtual=>"y8st07ef7u",
    :user=>{
            :id=>280,
            :name=>'foo'
    }
}


Foo_controller设置


Foo_controller setting

class Api::V1::FoosController < ApplicationController
    foos = Foo.all
    foos.each do |foo|
       foo.set_attribute('y8st07ef7u')
    end
    render json: foos.to_json(:methods => :virtual), status: 200
end

Foo_model设置

Foo_model setting

class Foo < ActiveRecord::Base

    belongs_to :user

    attr_accessor:virtual

    def set_attribute(path)
        self.virtual = path
    end
end

Foo_serializer设置

Foo_serializer setting

class FooSerializer < ActiveModel::Serializer
    attributes :id, :virtual
    has_one :user
end

Foo迁移设置

class CreateFoos < ActiveRecord::Migration
    def change
        create_table :foo do |t|

            t.references :user

        end
    end
end

用户模型

class User < ActiveRecord::Base
   has_many :foos
end

用户序列化器

class UserSerializer < ActiveModel::Serializer
    attributes :id, :name
    belongs_to :foo
end


当我用"foos"替换foo_controller中的"foo.to_json(:methods =>:virtual)"时,序列化程序启动,并且我在返回的json中得到一个用户对象,而不是user_id,但:virtual不在其中json.


When I replace "foo.to_json(:methods => :virtual)" in foo_controller with "foos", serializer kicks in and I get a user object inside the returned json instead of user_id, but :virtual is not in the json.

有什么方法可以使用活动模型序列化器获得具有虚拟属性和关联对象的对象.

Are there any ways I can get an object with both virtual attributes and associated object using active model serializer.

预先感谢您的帮助!

推荐答案

我知道了.非常简单.

我只需要在foo_serializer的属性中添加:virtual",并仅用"foos"替换"foo.to_json(:methods =>:virtual)"

I just had to add ":virtual" to attributes in the foo_serializer and replace "foo.to_json(:methods =>:virtual)" with just "foos"

这篇关于具有虚拟属性的活动模型序列化器-Rails 4的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 06:47