具有虚拟属性的活动模型序列化程序 - Rails 4 [英] active model serializer with virtual attribute - Rails 4

查看:19
本文介绍了具有虚拟属性的活动模型序列化程序 - 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 - User.

: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"并将foo.to_json(:methods =>:virtual)"替换为foos"

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

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆