您可以在Entity
模型創建此方法(最好的做法是使用奇異的名字型號。)
class Entity
def avatar_images
avatars = images.find(:all, :conditions => ['image_type = ?', 'avatar'])
if avatars.empty?
avatars = Image.find(:all, :conditions =>
['entity_id is null and image_type = ?', 'avatar'])
end
avatars
end
end
然後,只需在控制器中調用該方法即可獲取屬於該實體的頭像圖像,或者獲取屬於該實體的頭像圖像或默認圖像(如果沒有)。
@avatars = @entity.avatar_images
編輯:
這可能是一個好主意來概括這種方法接受的圖像類型的參數,使之更加靈活:
class Entity
def images_of_type(type)
list = images.find(:all, :conditions => ['image_type = ?', type])
if list.empty?
list = Image.find(:all, :conditions =>
['entity_id is null and image_type = ?', type])
end
list
end
end
然後在您的控制器:
@avatars = @entity.images_of_type('avatar')
感謝隊友。非常簡單,完全符合我的要求。 – Roganartu