if-else中的链接条件过多

时间:2013-03-25 16:11:15

标签: ruby-on-rails ruby

使用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 < ActiveRecord::Base
  belongs_to :country
  has_many :zone_shops
  has_many :shops, :through => :zone_shops
end

# zone_shop.rb
class ZoneShop < ActiveRecord::Base
  belongs_to :zone
  belongs_to :shop
end

# shop.rb
class Shop < ActiveRecord::Base  

end

2 个答案:

答案 0 :(得分:1)

请注意!x.blank? - &gt; 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

答案 1 :(得分:1)

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

# 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