jbuilder with If Condition

Harsha M V picture Harsha M V · Oct 24, 2015 · Viewed 8.1k times · Source

I am trying to display a key-value pair on some condition in the jbuilder like as follows

json.id plan.id
json.title plan.title
json.description plan.description
json.plan_date plan.plan_date.iso8601
json.start_time plan.start_time.strftime("%I:%M %p") if !plan.start_time.present?

Error

NoMethodError at /api/plans/16
==============================

> undefined method `strftime' for nil:NilClass

app/views/api/v1/plans/_plan.json.jbuilder, line 5
--------------------------------------------------

``` ruby
    1   json.id plan.id
    2   json.title plan.title
    3   json.description plan.description
    4   json.plan_date plan.plan_date.iso8601
>   5   json.start_time plan.start_time.strftime("%I:%M %p") if !plan.start_time.present?

Answer

Arup Rakshit picture Arup Rakshit · Oct 24, 2015

Well, the inline if modifier don't work with jubilder. I do write it like

if plan.start_time.present?
  json.start_time plan.start_time.strftime("%I:%M %p")
end