【问题标题】:Rails "The parameter passed to #in? must respond to #include?"Rails“传递给#in的参数?必须响应#include?”
【发布时间】:2017-03-11 00:27:52
【问题描述】:

作为此处另一个问题的后续,我已将以下代码添加到我的 records_controller.rb

if params[:order].in? %s[year artist title]
  # adds ORDER to the scope
  @records.merge!( Record.order("? DESC", params[:order]) )
end

然后我得到一个错误:

"The parameter passed to #in? must respond to #include?"

这是什么意思?我需要改变什么?

【问题讨论】:

    标签: ruby-on-rails error-handling include actioncontroller


    【解决方案1】:
    %s[year artist title]
    => :"year artist title"
    

    这是一个符号,猜你喜欢检查 param 是否是字符串之一。尝试改用%w

    if params[:order].in? %w[year artist title]
    

    【讨论】:

      【解决方案2】:

      来自documentation

      in?(another_object) 公开

      如果该对象包含在参数中,则返回 true。

      参数必须是响应 #include?

      任何对象

      include? 响应一个对象数组,该数组的格式应该是 %w[year artist title],但不是像您写的 %s[year artist title]

      那样的 symbol
      %w[year artist title] # => ["year", "artist", "title"] can be used for include? and in?
      %i[year artist title] # => [:year, :artist, :title] can be used for include? and in?
      
      %s[year artist title] # => :"year artist title" which is a symbol that can not be used for include? or in?
      

      【讨论】:

        【解决方案3】:

        另一种情况:

        如果您的数组是nil,您将收到同样的错误

        我遇到了同样的问题,但因为我没有为我的数组处理 nil

        my_string.in? my_array
        

        如果my_array = nil 我得到了:(The parameter passed to #in? must respond to #include?)

        为了解决这个问题,我刚刚更改了:

        my_string.in? my_array || []
        

        现在如果my_array = nil 我错了

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-10-23
          • 2020-05-27
          • 2021-12-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-08-27
          • 2020-05-15
          相关资源
          最近更新 更多