![](/img/trans.png)
[英]how to do a where with a condition both in the object and in an associated object
[英]How do I elegantly check for presence of both the object and associated objects?
我有一个实例变量@tally_property
,如果该对象上有photos
,我想循环浏览并显示它们。
所以我的代码片段看起来像这样:
<% if @tally_property.photos.present? %>
<% @tally_property.photos.each_with_index do |photo, index| %>
问题是基于上述情况,如果@tally_property
为nil,则整个第一行都会引发错误。
因此,有没有我可以做的“零”支票,它不笨重,即if @tally_property.nil?
我不想这样做if @tally_property.nil?
,在主要对象和关联上,都是优雅,红宝石和铁轨般的风格吗?
我将使用安全的导航运算符( &.
)并编写如下代码:
<% @tally_property&.photos&.each_with_index do |photo, index| %>
...
<% end %>
在Ruby 2.3.0+中,您可以使用安全导航操作符:
@tally_property&.photos
ActiveSupport具有一个.try
方法,该方法可以在旧版本的ruby中用于同一目的:
@tally_property.try(:photos)
您可以添加一个简单的条件,以便能够安全地遍历集合:
<% (@tally_property.try(:photos)||[]).each_with_index do |photo, index| %>
<% end %>
Rails 4添加了ActiveRecord::Relation#none
和行为更改,以便关联始终返回ActiveRecord::Relation
。 因此,完全可以接受这样写:
<% @tally_property.try(:photos).try(:each_with_index) do |photo, index| %>
<% end %>
升级您的应用程序之后。 或者您可以使用局部渲染:
<%= render partial: 'photos', collection: @tally_property.photos if @tally_property %>
这消除了编写迭代的需要。
使用&&
(或and
,它们各有各的甜蜜点)。
将其从Erb中取出一会儿,我通常会这样写:
if @tally_property and @tally_property.photos.present?
根据我可能使用的photos
:
if @tally_property and @tally_property.photos
也许:
if @tally_property and not @tally_property.photos.empty?
有时我会使用一个临时变量:
if (photos = @tally_property && @tally_property.photos)
photos.each #…
那种事
我会推荐这一集Ruby Tapas, 和/或对它进行更长时间(但还是很快)的介绍。
另一种方法是,只需选择与此tally_property相关的所有照片:
示例可能是这样的:
Photo.joins(:tally_property).each_with_index做| photo,index |
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.