5

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?
Harsha M V
  • 54,075
  • 125
  • 354
  • 529

2 Answers2

15

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
Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317
3

The problem is that you are not using parenthesis properly and therefore your if block is not evaluated properly.

Writing

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

is equivalent to:

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

the correct way of writing it is:

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

inline if modifiers work also on jbuilder.

coorasse
  • 5,278
  • 1
  • 34
  • 45