jsonify-rails icon indicating copy to clipboard operation
jsonify-rails copied to clipboard

Rendering a partial within a loop

Open lagartoflojo opened this issue 13 years ago • 4 comments

Hi, I'm trying to render a partial multiple times (for the index action) and it's only returning the last item:

Partial _child.json.jsonify

json.name child.name

File index.json.jsonify

@children.each do |child|
  json.ingest!(render partial: child)
end

Actual result:

{"name":"Pedrito"}

Expected result:

[{"name":"Horacio"},{"name":"Pepito"},{"name":"Pedrito"}]

I also tried:

@children.each do |child|
  json << json.ingest!(render partial: child)
end

But the result was:

{"name":"Pedrito","#<Jsonify::JsonObject:0x00000002333ef0>":null,"[#<Jsonify::JsonPair:0x00000002320df0 @key=\"name\", @value=\"Pepito\">]":null,"[#<Jsonify::JsonPair:0x00000002306658 @key=\"name\", @value=\"Pedrito\">]":null}

lagartoflojo avatar Oct 30 '11 03:10 lagartoflojo

I'll take a look today at your problem ... until I get that fixed, you could just skip the partial ...

@children.each do |child| json.name child.name end

On Oct 29, 2011, at 11:23 PM, lagartoflojo wrote:

Hi, I'm trying to render a partial multiple times (for the index action) and it's only returning the last item:

Partial _child.json.jsonify

json.name child.name

File index.json.jsonify

@children.each do |child|
 json.ingest!(render partial: child)
end

Actual result:

{"name":"Pedrito"}

Expected result:

[{"name":"Horacio"},{"name":"Pepito"},{"name":"Pedrito"}]

I also tried:

@children.each do |child|
 json << json.ingest!(render partial: child)
end

But the result was:

{"name":"Pedrito","#<Jsonify::JsonObject:0x00000002333ef0>":null,"[#<Jsonify::JsonPair:0x00000002320df0 @key=\"name\", @value=\"Pepito\">]":null,"[#<Jsonify::JsonPair:0x00000002306658 @key=\"name\", @value=\"Pedrito\">]":null}

Reply to this email directly or view it on GitHub: https://github.com/bsiggelkow/jsonify-rails/issues/5

bsiggelkow avatar Oct 30 '11 16:10 bsiggelkow

Thank you! Yes, that's how I generated the "expected result".

lagartoflojo avatar Oct 30 '11 17:10 lagartoflojo

Hi I am looking for the same thing. Any solutions for this?

sporto avatar Aug 07 '12 03:08 sporto

I have this working like this:

@children.each do | child |
    json << JSON.parse(render 'child', child: child)
end

Not very efficient because Jsonify is converting the partial into a string and JSON.parse is converting it back into a hash, but it works.

sporto avatar Aug 07 '12 04:08 sporto