簡體   English   中英

如何優雅地檢查對象和關聯對象的存在?

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

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM