views:

87

answers:

1

Hello there!

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  A: 
Foo.all(:fields=>[:title, :city, :state])
khelll