2011-09-14 36 views
1

說我有一個表中如此定義的:恢復出廠記錄,如果沒有其他的相關記錄存在

Entities has_many Images 
Images has_one Entity 

我在那有ENTITY_ID,我想爲默認沒有價值的圖像表中的記錄圖像爲任何新的實體。

當我使用:

@entities.images.find(:all, :conditions => ['image_type = ?', 'avatar]) 

我想從圖像表的默認記錄要返回當且僅當是當前實體

沒有圖像這是可能的,如果是這樣,怎麼樣?

謝謝。

回答

1

您可以在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') 
+0

感謝隊友。非常簡單,完全符合我的要求。 – Roganartu

0

如果你真的必須,你可以做這樣的事情在未來一段代碼,雖然我不會真的建議是:

class << self 
    def find (*arguments) 
     begin 
     result_set = super(*arguments) 
     rescue 
     result_set = [] 
     ensure 
     result_set = 
      Image.find(:first, 
        :conditions =>['entity_id is null and image_type = ?', 'avatar'] 
        ) if result_set.blank? 
     end 
     result_set 
    end 
    end 

的方式,爲什麼我不建議這樣做,是因爲它改變了正常的方式找到()的作品,我會建議只是做一個新的方法,它封裝了你想做的事,像什麼:

def find_or_default (*arguments) 
    begin 
     begin 
     result_set = Image.find(*arguments) 
     rescue 
     result_set = [] 
     ensure 
     result_set = 
      Image.find(:first, 
        :conditions =>['entity_id is null and image_type = ?', 'avatar'] 
        ) if result_set.blank? 
     end 
     result_set 
    end 
end 
+0

我修改了一下代碼,因爲我有一個變量w因爲真的不需要。 (繪製代碼的結果;)) –

相關問題