如何使用DataMapper仅获取模型的指定字段?

我无法找到在特定上下文中仅获取必要的模型字段的方法。 让我们说我有一个巨大的模型,有大约30个领域(属性)。 但是出于搜索目的,我只需要几个。

例:

class Foo include DataMapper::Resource property :id, Serial property :title, String, :length => 256 property :description, Text property :url, String, :length => 4096 property :city, String, :length => 64 property :country, String, :length => 64 property :state, String, :length => 64 property :created_at, Time property :updated_at, Time property :expires_at, Time ... etc fields ... end 

因此,对于前端(Web应用程序),大多数字段都被使用。 但对于搜索,我只需要说:标题,:城市,:州。 它很容易查询数据

 items = Foo.all(:title.like => 'Some stuff') 

然后我需要将获取的数据打包成JSON。 据我所知,有一个名为dm-serialize的DataMapper模块可以处理所有操作。

最后,我做输出包:

 response = {:error => 0, :count => items.length, :data => items} response.to_json 

但输出项目包含所有字段,而我只需要获取其中的一些字段。 由于某些原因,延迟加载不起作用。

问题是:如何指定要选择的模型字段?

 Foo.all(:fields=>[:title, :city, :state]) 

一直在绊倒这个。
另外,为#to_json方法提供:only选项,否则它将延迟加载尚未提取的方法。

 items.to_json(:only => [:title, :city, :state]) 

你必须自己构建json响应; 否则将发生其他字段的延迟提取。