我找不到在特定上下文中仅获取模型必要字段的方法。假设我有一个巨大的模型,它有大约 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
但是输出项具有所有字段,而我只需要获取其中的一些。由于某种原因,延迟加载不起作用。
问题是:如何指定要选择的模型字段?