if-else中的链接条件过多

使用Rails。 如何最好地重写country_photo

 # country.rb class Country < ActiveRecord::Base has_many :zones def country_photo if !zones.blank? && !zones.first.shops.blank? && !zones.first.shops.first.photos.blank? zones.first.shops.first.photos.first.url(:picture_preview) end end end # zones.rb class Zone  :zone_shops end # zone_shop.rb class ZoneShop < ActiveRecord::Base belongs_to :zone belongs_to :shop end # shop.rb class Shop < ActiveRecord::Base end 

请注意!x.blank? – > x.present? 。 无论如何,如果你可以在if进行分配(它们在Ruby中很常见),你可以写:

 def country_photo if (zone = zones.first) && (shop = zone.shops.first) && (photo = shop.photos.first) photo.url(:picture_preview) end end 

如果你喜欢花哨的抽象,用Ick你可以写:

 def country_photo zones.first.maybe { |zone| zone.shops.first.photos.first.url(:picture_preview) } end 

假设你想在视图中显示图像,我会做这样的事情:

 # show.html.haml - if @country.photo image_tag @country.photo.url(:picture_preview) # country.rb class Country < ActiveRecord::Base def photo zones.first.photo unless zones.blank? end end # zone.rb class Zone < ActiveRecord::Base def photo shops.first.photo unless shops.blank? end end # shop.rb class Shop < ActiveRecord::Base def photo photos.first unless photos.blank? end end