2016-02-15 73 views
1

尋找更清晰的方式來設置默認值,如果屬性尚未設置或已被刪除,並返回nil。ActiveRecord的默認值,如果屬性爲零

class Category < ActiveRecord::Base 
    has_and_belongs_to_many :restaurants 
    belongs_to :picture 

    def set_picture 
    if self.picture.nil? 
     Picture.default_pic 
    else 
     self.picture 
    end 
    end 
end 

class Picture < ActiveRecord::Base 
    belongs_to :review 

    def self.default_pic 
    Picture.new(url: "/assets/default.jpg") 
    end 
end 

# index.html.erb 
<%= image_tag category.set_picture.url %> 

類別有很多餐館,和餐館有很多評論。評論有一對一的圖片。類別應該被允許從其關聯的圖片之一中選擇,或者默認爲資產文件夾中的圖像。

#set_picture需要重構出來。希望對某種類型的回調:

class Category < ActiveRecord::Base 
    belongs_to :picture, defaults_to: Picture.default_pic 
end 

是否有一個回調,做到了上述?我可以創建一個嗎?還是我的框架錯了?

回答

4

我想你可以重寫訪問器並調用超級。如果返回零,則可以返回默認圖片:

class Category < ActiveRecord::Base 
    belongs_to :picture 

    def picture 
    super || Picture.default_pic 
    end 
end