2012-10-30 48 views
2

在Ruby 1.9.3p194中的Rails 3.2.8中,當在ActiveSupport :: Concern的包含塊中將一個數組傳遞給respond_to時在類定義需求通過調用模塊的acts_as_...方法包括在寶石導致:respond_to在[:json,:html]中導致未定義的方法`to_sym':Array

respond_to causes undefined method `to_sym' for [:json, :html]:Array 

,並在下一次請求時,我得到:

RuntimeError (In order to use respond_with, first you need to declare the formats your controller responds to in the class level): 
    actionpack (3.2.8) lib/action_controller/metal/mime_responds.rb:234:in `respond_with' 

在模塊的代碼,它是隻是做相當於:

formats = [:json, :html] 
respond_to formats 

其中格式配置在其他地方,因此它可以應用於指定爲acts_as_...的所有控制器。

我知道我這樣做是在一個類定義時,它的工作原理:

respond_to :json, :html 

所以,我怎麼能調用的respond_to一個變量,它的格式數組?

回答

2

respond_to法在導軌3.2.8相關部分是:

def respond_to(*mimes) 
    # ... 
    mimes.each do |mime| 
    mime = mime.to_sym 
    # ... 
    end 
    # ... 
end 

由於圖示操作者在respond_to使用時,它被纏繞在一個數組傳入數組,所以默劇是[[:json, :html]],和它試圖在數組上調用to_sym

如果調用respond_to具有可變包含數組,你需要使用的圖示(*)運算符,如:

formats = [:json, :html] 
respond_to *formats 

,將調用respond_to,如果你是在兩個參數發送

respond_to :json, :html 

或:

respond_to(:json, :html) 
相關問題