开发者

Rails - How to use TRY for nested records

开发者 https://www.devze.com 2023-03-18 17:16 出处:网络
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 th

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

精彩评论

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

关注公众号