Rails“参数传递给#in?必须回复#include?“

问题描述 投票:1回答:3

作为这里的另一个问题的后续,我已将以下代码添加到我的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
3个回答
3
投票

来自documentation

in?(another_object)public

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

参数必须是响应#include的任何对象?

include?响应一个对象数组,该数组应采用格式%w[year artist title]但不是符号,因为你已经写了%s[year artist title]

%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?

0
投票
%s[year artist title]
=> :"year artist title"

这是一个符号,猜你想检查param是否是其中一个字符串。尝试使用%w代替。

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

0
投票

另一种情况:

如果你的数组是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我弄错了

© www.soinside.com 2019 - 2024. All rights reserved.