[英]Rails/ActiveRecord - How can I make this more concise?
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. 似乎我必须做很多这样的事情,因为有些字段可以为空。
Is there a better way to write this? 有没有更好的方法来写这个?
I could handle it at the model layer but thats not really model layer functionality, as I understand. 我可以在模型层处理它,但根据我的理解,这并不能真正模拟层功能。
You can use delegate method supported by active record. 您可以使用活动记录支持的委托方法。
delegate :phone_number, :to => :person, :allow_nil => true
And call @house.phone_number
directly, avoiding the person
middleman too. 和呼叫@house.phone_number
直接,避免了person
中间人太多。 If phone is nil, this will also return nil. 如果手机是零,这也将返回零。
你可以使用@house.person.try(:phone_number)
These Strongly-Worded Suggestion of Demeter -type issues can certainly be wrapped up in the model by wrapping up the Person
's methods in the House
, exposing less information in the process. 这些对Demeter类型问题的强烈建议当然可以通过在House
包含Person
的方法来包含在模型中,从而在过程中暴露更少的信息。
def person_phone_number
@person.phone_number || ""
end
Kind of clunky; 有点笨重; you could also meta-program them in to place. 你也可以对它们进行元编程。
Or create helpers, or a combo of both. 或者创建助手或两者的组合。 This is a typical issue, and IMO there's nothing wrong with wrapping it up in the containing model. 这是一个典型的问题,IMO将其包含在包含模型中没有任何问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.