如何使用DataMapper仅获取模型的指定字段? [英] How to fetch only specified fields of model with DataMapper?

查看:67
本文介绍了如何使用DataMapper仅获取模型的指定字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找不到在特定上下文中仅获取模型的必要字段的方法。假设我有一个巨大的模型,其中包含约30个字段(属性)。但是出于搜索目的,我只需要几个。

I cant find the way to fetch only necessary fields of model in certain context. Let`s say i have a huge model which has about 30 fields (properties). But for a search purpose i need only couple of them.

示例:

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。像这样容易查询数据

So, for the front-end (web application) most of that fields are used. But for search i need let`s say only :title, :city, :state. Its easy to query data, like that

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

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

And then i need to pack fetched data into JSON. As far as i know, there is a module for DataMapper called dm-serialize which handles all that operations.

最后,我做输出软件包:

Finally, i do the package for output:

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

但是输出项目具有所有字段,而我需要只得到其中一些。出于某种原因,延迟加载无法正常工作。

But the output items have all the fields while i need to get only some of them. For some reason lazy loading does not work.

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

The question is: How to specify model fields you are going to select?

推荐答案

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

这篇关于如何使用DataMapper仅获取模型的指定字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆