2014-12-05 44 views
1

我目前正在使用RoR创建API,并且需要创建具有虚拟属性和关联对象的对象。具有虚拟属性的活动模型序列化程序 - Rails 4

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

下面是从foo_controller

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

返回的对象:虚拟是虚拟属性和user_id是关联表的一个id - 用户。

我的目标是让这个

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

Foo_controller设置

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设置

class Foo < ActiveRecord::Base 

    belongs_to :user 

    attr_accessor:virtual 

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

Foo_serializer设置

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

富迁移设定

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 

当我替换“foo.to_json(:方法=>:虚拟)“在foo_con中troller与“foos”,串行器踢,我得到一个用户对象内返回的JSON而不是user_id,但:虚拟不在JSON中。

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

非常感谢您的帮助!

回答

1

我想通了。这很简单。

我只需将“:virtual”添加到foo_serializer中的属性中,并用“foos”替换“foo.to_json(:methods =>:virtual)”