How to fetch only specified fields of model with DataMapper?

给你一囗甜甜゛ 提交于 2020-01-14 03:02:32

问题


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.

Example:

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

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')

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?


回答1:


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



回答2:


Been stumbling over this, too.
Also, provide the :only option to #to_json method, otherwise it will lazy load the ones not yet fetched.

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

You have to build the json response yourself; otherwise lazy fetches of the other fields will occur.



来源:https://stackoverflow.com/questions/1967017/how-to-fetch-only-specified-fields-of-model-with-datamapper

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!