2012-01-02 64 views
1

當在Datamapper的類中定義關聯時,您似乎無法默認獲取關聯的模型數據。使用DataMapper獲取相關模型(Ruby)

舉個例子:

class Song 
    include DataMapper::Resource 

    property :id,   Serial 
    property :name,   String 
    property :artist_id, Integer 

    belongs_to :artist 
end 

class Artist 
    include DataMapper::Resource 

    property :id,  Serial 
    property :name,  String 

    has n, :songs 
end 

Song.get(params[:id]).to_json 

歌曲查詢不執行默認與藝術家表的連接。在上面的例子中,你如何進行連接並獲得歌曲和歌曲?單獨查詢任何一個類都可以正常工作。請注意,這是一個現有的數據庫,不是通過DataMapper創建的。

在此先感謝!

回答

2

我懷疑你正在嘗試做什麼目前是不可能的。使用DataMapper,您可以隨時輕鬆加載歌曲的藝術家等屬性,甚至可以使用他們所謂的戰略性的熱切加載,這被描述爲here。但即使該財產已經被加載,它也不會包含在由to_json返回的結果中。

所以你只剩下兩種選擇:

  1. 你可以簡單地做一些額外的編碼組成一個散列,然後就可以使用to_json
song = Song.get(params[:id]) 
json = song.attributes.merge({:artist => song.artist.attributes}).to_json 
  1. 可以包括宋類本身的類似代碼:
def to_json 
    self.attributes.merge({:time_zone => self.time_zone.attributes}).to_json 
end 

如果您使用#2,您還必須require 'json'

請注意,DataMapper使to_json遞歸工作並不是一個好主意。否則,您可能會返回整個數據庫:P

相關問題