1

使用 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
4

2 回答 2

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
于 2013-03-25T16:53:53.300 回答
1

请注意!x.blank?-> x.present?。无论如何,如果您可以在ifs 中进行分配(它们在 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
于 2013-03-25T16:26:13.413 回答