Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/61.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby-on-rails-4/2.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 关系。Rails 4中的所有弃用_Ruby On Rails_Ruby On Rails 4_Activerecord - Fatal编程技术网

Ruby on rails 关系。Rails 4中的所有弃用

Ruby on rails 关系。Rails 4中的所有弃用,ruby-on-rails,ruby-on-rails-4,activerecord,Ruby On Rails,Ruby On Rails 4,Activerecord,如果我在Rails 3中执行以下操作: users=User.where("last_name like ?","s%").all 它返回一个数组,我可以通过执行以下操作立即将其视为数组: users.unshift(User.new) 在Rails 4中.all语句给出了弃用警告: 弃用警告:关系#全部已弃用。如果你想 如果要加载关系,可以调用#load 现在,all返回一个关系,假设下面两行代码是等价的: users=User.where("last_name like ?","s%")

如果我在Rails 3中执行以下操作:

users=User.where("last_name like ?","s%").all
它返回一个数组,我可以通过执行以下操作立即将其视为数组:

users.unshift(User.new)
在Rails 4中.all语句给出了弃用警告:

弃用警告:关系#全部已弃用。如果你想 如果要加载关系,可以调用#load

现在,all返回一个关系,假设下面两行代码是等价的:

users=User.where("last_name like ?","s%").all

users=User.where("last_name like ?","s%")
换句话说,变量“users”现在是一个关系而不是数组

我的问题是,由于“users.unshift”语句仍然对关系起作用,并将其转换为数组,因此如何才能使关系被视为数组。这是不是在强迫一种关系


我真的应该使用“.load”吗。它似乎不是必需的,但在逻辑上应该是。

ActiveRecord::Relation
使用
method\u missing
将大多数数组方法委托给
array
。取消换档是一个重要因素

请参见此处的来源:

请参阅的评论


ActiveRecord
集合的行为类似于数组,因此您可以调用任何数组 方法(尽管它们会将其转换为数组,以便 丢失特殊的
ActiveRecord
方法)。您不必调用
#load
让它像数组一样工作。只要假装
ActiveRecord
集合是一个数组,你会没事的


ActiveRecord
集合的行为类似于数组,因此您可以对其调用任何数组方法(尽管它们会将其转换为数组,因此您将丢失特殊的
ActiveRecord
方法)。您不必调用
#load
使其像数组一样工作。只要假设
ActiveRecord
集合是一个数组,就可以了。
def array_delegable?(method)
  Array.method_defined?(method) && BLACKLISTED_ARRAY_METHODS.exclude?(method)
end

def method_missing(method, *args, &block)
  if @klass.respond_to?(method)
    scoping { @klass.public_send(method, *args, &block) }
  elsif array_delegable?(method)
    to_a.public_send(method, *args, &block)
  elsif arel.respond_to?(method)
    arel.public_send(method, *args, &block)
  else
    super
  end
end