2014-12-05 40 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)」