xoail
xoail

Reputation: 3064

Rails erb Json view conditional rendering

When I try this, I get {a: 1, b:} for c not present. When c is present I get {a:1,b:1} which is right. But how can I hide the node b conditionally so that I could only get {a:1}?

{"a":   <%= json @teams.count %>
,"b":   <%= json @teams.num if @c.present? %>}

Upvotes: 0

Views: 413

Answers (1)

PinnyM
PinnyM

Reputation: 35531

You can pass a ruby hash to json and it will figure it out correctly

<%= json( a: @teams.count, b: (@teams.num if @c.present?) ) %>

The problem with your method is that you are trying to render the string yourself, but nil is being rendered as blank space instead of an empty string ''. You could theoretically fix it like this:

{"a":   <%= json @teams.count %>
,"b":   <%= json(@c.present? ? @teams.num : '' %>}

but you can avoid most of the hassle if you use the first method.

Upvotes: 1

Related Questions