2012-02-12 112 views
1

我有以下兩種型號的觀察員:instance_of?返回意外的結果

class MyObserver < ActiveRecord::Observer 
    observe :my_first_model, :my_second_model 

    def after_create(record) 
    x = if record.instance_of?(MyFirstModel) 
     # x is set to one thing 
    elsif record.instance_of?(MySecondModel) 
     # x is set to another thing 
    end 

    # use x in a common way 
    end 
end 

正如你所看到的,我設置x的東西不同,這取決於它的創建是被觀察的模型。

我使用instance_of?kind_of?獲得了意想不到的結果。例如,我可以做Rails.logger.debug record.class.name並參見MyFirstModel,但record.instance_of?(MyFirstModel)返回false。

有沒有人遇到過這個?我正在使用Ruby 1.9.3和Rails 3.1。

與此同時,我打算採取record.class.name.inquiry.MyFirstModel?或類似的東西。

回答

1

爲此使用一個case聲明。

def after_create(record) 
    x = case record 
    when MyFirstModel 
     # x is set to one thing 
    when MySecondModel 
     # x is set to another thing 
    else ; return false 
    end 

    # use x in a common way 
end 
+0

感謝您的回答,@gg_s。我不知道你可以在類似的case語句中使用類名,以便學到新東西。可悲的是,它沒有解決問題,「記錄」沒有被正確識別。 – tristanm 2012-02-13 02:31:11