使用Rails。如何最好地重写country_photo
?if-else中的链接条件过多
# 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
当你有那些有多深的关联,你不能做任何事情。但避免深层关联的一种方法是在'country'模型中存储'photo_id',其中'belongs_to:photo'。还有一种方法可以做到没有if-else的情况,即zone.try(:first).try(:shops).try(:first).try(:photos).try(:first).try(:url ).try(:picture_preview)' – codeit 2013-03-25 16:27:14