neuromancer
neuromancer

Reputation: 55499

How to use datamapper to return table entries as a json formatted string?

Let's say I have a table, and I want to return the values for every entry in the table for a particular field. How can I use datamapper to return these values as a json formatted string?

Upvotes: 0

Views: 323

Answers (1)

ujifgc
ujifgc

Reputation: 2255

Am I getting it right?

Hash[Page.all( :fields => [:id, :title] ).map{|p|[p.id,p.title]}].to_json

DEBUG (0.000176) SELECT `id`, `title` FROM `pages` ORDER BY `id`
> {"1":"page A","2":"page B"}

Or, if you want an array

Page.all( :fields => [:title] ).map(&:title).to_json

DEBUG (0.000038) SELECT `title` FROM `pages` ORDER BY `id`
> ["page A","page B"]

Upvotes: 2

Related Questions