简体   繁体   English

Rails / ActiveRecord - 我怎样才能使这更简洁?

[英]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.

相关问题 如何使这种方法更简洁? - How can I make this method more concise? 如何使用 Rails 6.0.3.3 和 Ruby 2.7.1 使这个 ActiveRecord 调用更高效 - How to make this ActiveRecord call more efficient with Rails 6.0.3.3 and Ruby 2.7.1 Rails ActiveRecord。 我如何处理不止一个? - Rails ActiveRecord. how can I deal with belong_to more than one? 如何使Rails异常信息更丰富? - How can I make a rails exceptions more informative? 如何使Rails助手更加面向对象 - How can I make rails helpers more object-oriented 如何使这个Ruby on Rails页面更有效? - How can I make this Ruby on Rails page more efficient? 如何使这组Rails 3.1查询更高效? - How can I make this set of Rails 3.1 queries more efficient? 如何使我的ActiveRecord对象在Ruby on Rails中仅存在5分钟? - How can I make my ActiveRecord objects only exist for 5 minutes in Ruby on Rails? 在Rails中,如何为两个以不同方式相互引用的模型建立ActiveRecord关联? - In Rails, how can I make ActiveRecord associations for two models that reference each other in different ways? 如何在Rails ActiveRecord中的one_to_many关系中进行级联删除? - How can I make a cascade deletion in a one_to_many relationship in Rails ActiveRecord?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM