Rails/ActiveRecord - 我怎样才能使它更简洁? [英] Rails/ActiveRecord - How can I make this more concise?

查看:30
本文介绍了Rails/ActiveRecord - 我怎样才能使它更简洁?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我看来,我有如下一行:

In my view I have a line such as the following:

<%= @house.person.phone_number unless @house.person.nil?  %>

似乎我必须做很多这样的事情,因为有些字段可以为空.

It seems like I have to do this sort of thing a lot as some fields are nullable.

有没有更好的写法?

我可以在模型层处理它,但据我所知,这并不是真正的模型层功能.

I could handle it at the model layer but thats not really model layer functionality, as I understand.

推荐答案

您可以使用@house.person.try(:phone_number)

这篇关于Rails/ActiveRecord - 我怎样才能使它更简洁?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆