0

I have a code section like the following:

users = User.all(:fname => "Paul")

This of course results in getting all users called "Paul". Now I only need some of the columns available for each user which leads to replacing the above line by something like this:

users = User.all(:name => "Paul", :fields => [:id, :fname, :lname, :email])

Until now everything works as expected. Unfortunately now I want to work with users but as soon as I use something like users.to_json, also the other columns available will be lazy-loaded even due the fact, that I don't need those. What's the correct or at least a good way to end up with users only containing the attributes for each user that I need?

An intermediate object like suggested in How to stop DataMapper from double query when limiting columns/fields? is not a very good option as I have a lot of places where would need to define at least twice which fields I need and also I would loose the speed improvement gained by loading only the needed data from the DB. In addition such an intermediate object also seems to be quite ugly to build when having multiple rows of the DB selected (=> multiple objects in a collection) instead of just one.

Disenchant
  • 118
  • 4

1 Answers1

0

If you usually works with the collection using json I suggest overriding the as_json method in your model:

def as_json(options = nil)
  # this example ignores the user's options
  super({:only => [:fname]}.merge(options || {}))
end

You are able to find more detailed explanation here http://robots.thoughtbot.com/better-serialization-less-as-json

MikeZ
  • 485
  • 4
  • 13
  • That would work perfectly if I only had the User model and always needed the same attributes. Unfortunately I have many different models and for each model different use-cases where I need different attributes. In addition if I don't get it wrong, your solution would still let DataMapper trigger a second database query to get the unneeded attributes/columns. – Disenchant Mar 16 '14 at 13:38