respond_to导致[:json,:html]:Array的未定义方法`to_sym'

时间:2012-10-30 18:05:49

标签: ruby-on-rails ruby-on-rails-3.1 respond-to respond-with

在Ruby 1.9.3p194中的Rails 3.2.8中将数组传递给ActiveSupport :: Concern的包含块中的respond_to时,通过调用acts_as_...在类定义中按需包含包含在gem中的模块中的方法导致:

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?

1 个答案:

答案 0 :(得分:2)

Rails 3.2.8中respond_to方法的相关部分是:

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

因为在respond_to中使用了splat运算符,所以它将传入的数组包装在一个数组中,所以mimes是[[:json, :html]],并且它试图在数组上调用to_sym

如果使用包含数组的变量调用respond_to,则需要使用splat(*)运算符,例如:

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

这将调用respond_to,就像你发送两个参数一样:

respond_to :json, :html

或:

respond_to(:json, :html)