带有 If 条件的 jbuilder
jbuilder with If Condition
我正在尝试在 jbuilder 中的某些条件下显示 key-value
对,如下所示
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?
错误
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?
嗯,内联 if
修饰符不适用于 jubilder。我是这样写的
if plan.start_time.present?
json.start_time plan.start_time.strftime("%I:%M %p")
end
问题是您没有正确使用括号,因此您的 if
块没有被正确评估。
写作
json.start_time plan.start_time.strftime("%I:%M %p") if !plan.start_time.present?
相当于:
json.start_time(plan.start_time.strftime("%I:%M %p") if !plan.start_time.present?)
正确的写法是:
json.start_time(plan.start_time.strftime("%I:%M %p")) if !plan.start_time.present?
内联 if
修饰符也适用于 jbuilder。
我正在尝试在 jbuilder 中的某些条件下显示 key-value
对,如下所示
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?
错误
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?
嗯,内联 if
修饰符不适用于 jubilder。我是这样写的
if plan.start_time.present?
json.start_time plan.start_time.strftime("%I:%M %p")
end
问题是您没有正确使用括号,因此您的 if
块没有被正确评估。
写作
json.start_time plan.start_time.strftime("%I:%M %p") if !plan.start_time.present?
相当于:
json.start_time(plan.start_time.strftime("%I:%M %p") if !plan.start_time.present?)
正确的写法是:
json.start_time(plan.start_time.strftime("%I:%M %p")) if !plan.start_time.present?
内联 if
修饰符也适用于 jbuilder。