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

Dan*_*off 1 ruby 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
Run Code Online (Sandbox Code Playgroud)

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

items = Foo.all(:title.like => 'Some stuff')
Run Code Online (Sandbox Code Playgroud)

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

最后,我做输出包:

response = {:error => 0, :count => items.length, :data => items}
response.to_json
Run Code Online (Sandbox Code Playgroud)

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

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

khe*_*lll 7

Foo.all(:fields=>[:title, :city, :state])
Run Code Online (Sandbox Code Playgroud)