2014-11-14 60 views
0

你好我已經爲我的Rails應用程序創建了一個基本的REST控制器,我努力讓我的ActiveRecord模型加入請求。在ActiveRecord中自動加入關係

我的目標是要完成這樣的事情:

請求:GET /預約 響應:

[ 
    { 
     "id":1, 
     "customer_id":3, 
     "customer":{ 
      "name":"John Doe" 
     }, 
     "date":"2011-11-11T00:00:00.000Z", 
     "created_at":null, 
     "updated_at":null, 
     "employee_id":1, 
     "employee":{ 
      "name":"Jane Doe" 
     } 
    } 
] 

但是我只是得到這個:

[ 
    { 
     "id":1, 
     "customer_id":3, 
     "date":"2011-11-11T00:00:00.000Z", 
     "created_at":null, 
     "updated_at":null, 
     "employee_id":1 
    } 
] 

這裏是我的基地REST控制器:http://pastebin.com/gQqBNeCH 你可以閱讀整個事情,如果你想,否則你可以閱讀代碼我是FOC使用上:

def index 
    @objects = get_class().all 

    @objects.each do |x| 
    x.get_relations 
    end 

    render json: @objects 
end 

這裏是我的約會模式

class Appointment < ActiveRecord::Base 

    belongs_to :customer 
    belongs_to :employee 

    attr_accessor :customer 

    validates :customer_id, presence: true, :numericality => { 
    :only_integer => true, 
    :allow_blank => false, 
    :greater_than => 0 
    } 

    validates :employee_id, :numericality => { 
    :only_integer => true, 
    :allow_blank => false, 
    :greater_than => 0 
    } 

    validates :date, presence: true 

    def get_relations 
    @customer = Customer.find(self.customer_id) 
    end 

end 

我原來的方法,只是使用像這樣的成員變量:

def get_relations 
    @customer = Customer.find(self.customer_id) 
end 

但是它看起來像ActiveRecord的具有某種它使用render運行的序列化方法。有關如何將我的belongs_to關係附加到該對象的任何建議?

+0

+1 ......對於寫得很好,格式化的問題。好人!!!用於JBuilder的 – 2014-11-14 16:44:36

回答

2

如果要更改AR將對象渲染爲json的方式,可以覆蓋模型中的as_json方法(http://apidock.com/rails/ActiveModel/Serializers/JSON/as_json)。但是這意味着將演示信息放入您的模型中,我不是那麼喜歡。

您還可以包括的關係在您的電話to_json

render :json => @objects.to_json(:include => :relation) 

但在你的情況,因爲你正在構建的API我會考慮一些更高級的JSON格式選項如RABLJBuilder

+0

+1 ......明確地講有很多值! – 2014-11-14 17:30:44

+0

如果需要,您也可以簡單地使用json.erb或json.ruby視圖。如果你不想在你的應用程序中獲得太多的寶石,這是另一個有效的選擇。 – 2014-11-14 17:33:53

+0

RABL將是最好的選擇。您可以在哪裏創建具有關係的節點。 – 2014-11-14 18:43:21

0

你將不得不把它列入你的JSON響應明確

def index 
    @objects = get_class().all 
    render json: @objects.to_json(:include => [:employee, :company]) 
end