2010-10-01 39 views
1

觀察員,我有以下觀察:Rails 3的觀察 - 想學習如何實現多個模型

class NewsFeedObserver < ActiveRecord::Observer 
    observe :photo, :comment 

    def after_create(record) 
    end 
end 

什麼了,我想學習如何做的是增加一個開關/ IF在after_create聲明,所以我知道該模型的創建

喜歡的東西:

after_create(record) 
switch model_type 
case "photo" 
do some stuff 
case "comment" 
do some other stuff 
end 

或更容易想象:

if record == 'Photo' 

如何記錄並確定型號名稱?

回答

1

您需要設置獨立的觀察員不同的模型

所以對於用戶=> UserObserver,照片=> PhotoObserver

你需要告訴Rails應用程序使用什麼觀察員,您在配置指定/ environment.rb

至少這是標準的方式。有關詳細信息

http://guides.rubyonrails.org/active_record_validations_callbacks.html#observers

+0

這實際上工作...「record.class.name」這將是很好找到一種方式來獲得行動... CREATE,UDPATE等... – AnApprentice 2010-10-01 02:40:01

3

在評論,我注意到你發現這個工程,並使用record.class.name但是這不是很地道的紅寶石。 Ruby case聲明使用===進行比較,如果您正確實施它,它將很適合您。

class NewsFeedObserver < ActiveRecord::Observer 
    observe :photo, :comment 

    def after_create(record) 
    case record 
     when Photo 
     # do photo stuff 
     when Comment 
     # do comment stuff 
     else 
     # do default stuff 
    end 
    end 
end 

這實質上轉換爲:

if Photo === record 
    # do photo stuff 
elsif Comment === record 
    # do comment stuff 
else 
    # do default stuff 
end 

我勸你要注意以下幾點:

class Sample 
end 

s = Sample.new 

Foo === s # true uses Class#=== 
s === Foo # false uses Object#=== 

===Class不同的方式實現和Object