2012-01-02 66 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

相关问题