gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 17:04:24 24 4
gpt4 key购买 nike

我找不到在特定上下文中只获取模型必要字段的方法。假设我有一个巨大的模型,它有大约 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 中。据我所知,有一个名为 dm-serialize 的 DataMapper 模块可以处理所有这些操作。

最后,我做了输出包:

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

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

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

最佳答案

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

关于ruby - 如何使用 DataMapper 仅获取模型的指定字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1967017/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com