我无法找到在特定情况下只提取必要的模型字段的方法。假设我有一个拥有30个字段(属性)的巨大模型。但为了搜索目的,我只需要其中的几个。如何仅使用DataMapper获取模型的指定字段?
实施例:
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
但输出项目拥有所有的领域,而我只需要获得其中的一些。由于某些原因,懒加载不起作用。
问题是:如何指定您要选择的模型字段?
谢谢!我想知道如何在使用to_json时不强制延迟加载 – vitorbal 2012-06-12 20:45:58