开发者

Rails - How to use TRY for nested records

I have the following:

:caption => thread.thread_widgets.first.widgetable.title

That works fine if the thread has a thread_widget, which is optional. Given it's optional, if the thread has no thread_widgets, then this errors with

undefined method `widgetable' for nil:NilClass

Is there a way I can use try(开发者_高级运维) so that the error doesn't kill the page?

Thanks


:caption => (o = thread.thread_widgets.first) && o.widgetable.title

But you asked for Object#try, so:

:caption => thread.thread_widgets.first.try(:widgetable).try(:title)


Another better option is to use the Safe Navigation Operator &. as follow:

:caption => thread.thread_widgets.first&.widgetable&.title

Reference:
http://mitrev.net/ruby/2015/11/13/the-operator-in-ruby/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜