[英]How do I elegantly check for presence of both the object and associated objects?
I have an instance variable @tally_property
, and if there are photos
on that object I would like to cycle through the photos and show them. 我有一个实例变量
@tally_property
,如果该对象上有photos
,我想循环浏览并显示它们。
So my code snippet looks like this: 所以我的代码片段看起来像这样:
<% if @tally_property.photos.present? %>
<% @tally_property.photos.each_with_index do |photo, index| %>
The issue is that based on the above, if @tally_property
is nil, then the entire first line throws an error. 问题是基于上述情况,如果
@tally_property
为nil,则整个第一行都会引发错误。
So is there a 'nil' check I can do that isn't bulky, ie I don't want to do if @tally_property.nil?
因此,有没有我可以做的“零”支票,它不笨重,即
if @tally_property.nil?
我不想这样做if @tally_property.nil?
, on both the primary object and the association, and is elegant and ruby & rails-esque? ,在主要对象和关联上,都是优雅,红宝石和铁轨般的风格吗?
In Ruby 2.3.0+ you can use the safe navigation operator: 在Ruby 2.3.0+中,您可以使用安全导航操作符:
@tally_property&.photos
ActiveSupport has a .try
method that can be used to the same end in older versions of ruby: ActiveSupport具有一个
.try
方法,该方法可以在旧版本的ruby中用于同一目的:
@tally_property.try(:photos)
You can add a simple conditional to be able to safely iterate through the collection: 您可以添加一个简单的条件,以便能够安全地遍历集合:
<% (@tally_property.try(:photos)||[]).each_with_index do |photo, index| %>
<% end %>
Rails 4 adds ActiveRecord::Relation#none
and a change in behaviour so that associations always return a ActiveRecord::Relation
. Rails 4添加了
ActiveRecord::Relation#none
和行为更改,以便关联始终返回ActiveRecord::Relation
。 So its perfectly acceptable to write: 因此,完全可以接受这样写:
<% @tally_property.try(:photos).try(:each_with_index) do |photo, index| %>
<% end %>
After upgrading your app. 升级您的应用程序之后。 Or you can use a partial and render:
或者您可以使用局部渲染:
<%= render partial: 'photos', collection: @tally_property.photos if @tally_property %>
Which removes the need for writing the iteration. 这消除了编写迭代的需要。
Use &&
(or and
, they each have their sweetspot). 使用
&&
(或and
,它们各有各的甜蜜点)。
Taking it out of Erb for a moment, I would generally write something like this: 将其从Erb中取出一会儿,我通常会这样写:
if @tally_property and @tally_property.photos.present?
Depending on photos
I might use: 根据我可能使用的
photos
:
if @tally_property and @tally_property.photos
or perhaps: 也许:
if @tally_property and not @tally_property.photos.empty?
Sometimes I'll use a temporary variable: 有时我会使用一个临时变量:
if (photos = @tally_property && @tally_property.photos)
photos.each #…
That kind of thing. 那种事
I would recommend this episode of Ruby Tapas, And/Or for a longer (but still quick) look at it. 我会推荐这一集Ruby Tapas, 和/或对它进行更长时间(但还是很快)的介绍。
One more way, just select all photos connected to this tally_property: 另一种方法是,只需选择与此tally_property相关的所有照片:
example how it might be: 示例可能是这样的:
Photo.joins(:tally_property).each_with_index do |photo, index| Photo.joins(:tally_property).each_with_index做| photo,index |
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.