How to fetch only specified fields of model with DataMapper?
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开发者_StackOverflow :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?
Foo.all(:fields=>[:title, :city, :state])
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.
精彩评论