1

我找不到在特定上下文中仅获取模型必要字段的方法。假设我有一个巨大的模型,它有大约 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 应用程序),大部分字段都被使用。但是对于搜索,我只需要说:title,:city,:state。它很容易查询数据,就像那样

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

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

最后,我做了输出包:

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

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

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

4

2 回答 2

7
Foo.all(:fields=>[:title, :city, :state])
于 2009-12-27T21:20:22.230 回答
4

也被这个绊倒了。
另外,提供方法:only选项#to_json,否则它将延迟加载尚未获取的选项。

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

您必须自己建立json响应;否则将发生对其他字段的惰性获取。

于 2012-02-20T10:32:05.100 回答