Method sort_by is deprecated - Possible solutions?

你说的曾经没有我的故事 提交于 2020-07-22 07:52:05

问题


my current rails project is giving a warning of -

DEPRECATION WARNING: Method sort_by is deprecated and will be removed in Rails 5.1, as ActionController::Parameters no longer inherits from hash.

I've searched for this warning as well as potential fixes but can't find anything at all regarding it. I'm wondering if anybody here would have any suggestions, fixes or replacements for sort_by? If this is an easy solution I apologies as I'm still learning rails.

Thanks for taking the time to read and/or answer.

Rails -v 5.0.7.2 | Ruby -v 2.6.4


回答1:


You can sort by anything using plain old Ruby sort. Here's an example that sorts instances of Foo by key or val, forward and backward:

class Foo
  attr_reader :key, :val

  def initialize(key, val)
    @key = key
    @val = val
  end

  def to_s
    "#{key}: #{val}"
  end
end

x = Foo.new('x', 1)
y = Foo.new('y', 2)

array = [x, y]

puts array.sort { |a, b| a.key <=> b.key }
puts array.sort { |a, b| b.key <=> a.key }
puts array.sort { |a, b| a.val <=> b.val }
puts array.sort { |a, b| b.val <=> a.val }



回答2:


With Rails 5, ActionController::Parameters will no longer inherit from HashWithIndifferentAccess.

Inheriting from `HashWithIndifferentAccess` allowed users to call any
enumerable methods on `Parameters` object, resulting in a risk of losing the
`permitted?` status or even getting back a pure `Hash` object instead of
a `Parameters` object with proper sanitization.

Take a look at this change

If you need to convert ActionController::Parameters in a true hash then it supports to_h method. Also ActionController::Parameters will continue to have methods like fetch, slice, slice!, except, except!, extract!, delete etc. You can take a detailed look at them here.



来源:https://stackoverflow.com/questions/60865822/method-sort-by-is-deprecated-possible-solutions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!