简体   繁体   English

Rails erb Json视图条件渲染

[英]Rails erb Json view conditional rendering

When I try this, I get {a: 1, b:} for c not present. 尝试此操作时,我得到{a:1,b:},因为c不存在。 When c is present I get {a:1,b:1} which is right. 当c存在时,我得到{a:1,b:1}是正确的。 But how can I hide the node b conditionally so that I could only get {a:1}? 但是,如何才能有条件地隐藏节点b,以便只能得到{a:1}?

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

You can pass a ruby hash to json and it will figure it out correctly 您可以将ruby哈希传递给json ,它将正确找出

<%= 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 '' . 方法的问题是您试图自己渲染字符串,但是nil被渲染为空白而不是空字符串'' 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. 但是如果您使用第一种方法,则可以避免大部分麻烦。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM