yee379
yee379

Reputation: 6762

rails jbuilder - just an array of strings

i have a controller that returns an array of ActiveRecord objects and a jbuilder view to generate the json (all standard stuff). works great if i want for example an array of hashes.

so for example i have:

json.array!(@list) do |l|
    json.( l, :field )
end

which returns

[
  { "field": "one" },
  { "field": "two" },
  { "field": "three" }
]

however, i want just an array of strings; such that my json is

[
  "one",
  "two",
  "three"
]

whats should my jbuilder file be?

Upvotes: 28

Views: 25115

Answers (2)

Ilya Novojilov
Ilya Novojilov

Reputation: 889

If you want Array as a value for some key, this will work:

json.some_key [1, 3, 4]

Upvotes: 6

irmco
irmco

Reputation: 924

A bit late but this will work:

json.array! @list

But consider to use it in a block to create a JSON pair:

json.data do
  json.array! @list  
end

# => { "data" : [ "item1", "item2", "item3" ] }

Upvotes: 60

Related Questions