Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 在基于ActiveResource的插件中重写Array.to_参数会有什么后果_Ruby On Rails_Ruby_Activeresource - Fatal编程技术网

Ruby on rails 在基于ActiveResource的插件中重写Array.to_参数会有什么后果

Ruby on rails 在基于ActiveResource的插件中重写Array.to_参数会有什么后果,ruby-on-rails,ruby,activeresource,Ruby On Rails,Ruby,Activeresource,基于资源的活动类: Contact.search(:email => ['bar@foo.com','foo@bar.com']) 将产生以下结果: ?email[]=bar@foo.com&email[]=foo@bar.com 我正在使用的特定API要求: ?email=bar@foo.com&email=foo@bar.com 因此,我发现: ActiveResource调用: # Find every resource find_every(options)

基于资源的活动类:

Contact.search(:email => ['bar@foo.com','foo@bar.com'])
将产生以下结果:

?email[]=bar@foo.com&email[]=foo@bar.com
我正在使用的特定API要求:

?email=bar@foo.com&email=foo@bar.com
因此,我发现:

ActiveResource调用:

# Find every resource
find_every(options)
这要求:

  # Builds the query string for the request.
  def query_string(options)
    "?#{options.to_query}" unless options.nil? || options.empty?
  end
因此,如果我更新:

class Array
  # Converts an array into a string suitable for use as a URL query string,
  # using the given +key+ as the param name.
  #
  # ['Rails', 'coding'].to_query('hobbies') # => "hobbies%5B%5D=Rails&hobbies%5B%5D=coding"
  def to_query(key)
    prefix = "#{key}[]"
    collect { |value| value.to_query(prefix) }.join '&'
  end
end
为此:

class Array
  # Converts an array into a string suitable for use as a URL query string,
  # using the given +key+ as the param name.
  #
  # ['Rails', 'coding'].to_query('hobbies') # => "hobbies%5B%5D=Rails&hobbies%5B%5D=coding"
  def to_query(key)
    prefix = "#{key}"
    collect { |value| value.to_query(prefix) }.join '&'
  end
end
它起作用了!!然而,我并不特别乐意重新定义Array.to_param,因为这可能会有无法预见的问题,尤其是当这个插件需要在rails中工作时


有没有其他方法可以只修补我的版本?

我绝对建议不要用猴子修补那样的数组方法。如果只有一个模型,是否可以覆盖搜索方法

class Contact
  def self.search(options={})
    super(options).gsub('[]','')
  end
end

由于这种行为在我使用的API中是标准的,所以我能够将这个补丁添加到我的ActiveRecord::基类中

  def query_string(options)
    begin
      super(options).gsub('%5B%5D','')
    rescue
    end
  end

感谢比灵顿为我指明了正确的方向。

谢谢比灵顿,谢谢你的回复,我找到了更好的解决方案-如下所示。